Problem · Matrix

Cave Advanture

Learn this problem
HardMetaOA
See Meta hiring insights

Problem statement

A cave is represented by a rectangular map of N rows and M columns. A period . marks a safe chamber, while X marks an unsafe chamber that cannot be entered.

The expedition starts at [0,0] and must reach the exit at [N-1,M-1]. From [r,c], explorers may move to [r,c-1], [r,c+1], or [r+1,c]. They cannot move upward, leave the map, enter an unsafe chamber, or revisit a chamber.

Return the maximum number of distinct safe chambers that can be visited along a valid route from the entrance to the exit. Return -1 when the exit cannot be reached.

Function

allAboutCave(A: String[]) → int

Examples

Example 1

A = ["..X.","...X","....","X..."]return = 9

A longest valid route starts at the top-left chamber, moves only left, right, or down without revisiting a chamber, reaches the bottom-right exit, and visits 9 safe chambers.

Example 2

A = [".X...",".X...","...X."]return = -1

The safe regions cannot be connected from the entrance to the exit without moving upward or crossing an unsafe chamber, so the exit is unreachable.

Example 3

A = ["......",".XXXX.","...X..","...X.X","......"]return = 14

The longest valid route reaches the exit while visiting 14 distinct safe chambers. It never moves upward or re-enters a chamber.

More Meta problems

drafts saved locally
public int allAboutCave(String[] A) {
  // write your code here
}
A["..X.","...X","....","X..."]
expected9
checking account