657. Landlocked Cells
An archipelago is mapped on a rectangular grid: 1 is a land cell and 0 is open sea. A traveller can walk between land cells that share a side (up, down, left or right). A traveller standing on a land cell in the first row, last row, first column or last column of the map can step off the map and leave the archipelago.
A land cell is landlocked when a traveller who starts on it can never leave the map by any sequence of walks over land. Return the number of landlocked land cells. If every land cell can eventually leave, or there is no land at all, return 0. Use O(R * C) time and O(R * C) extra space, with an iterative search.
Example 1
- Input:
- grid = [[0,1,0,0,0,0],[0,1,1,0,0,0],[0,0,0,1,1,0],[0,0,0,1,1,0],[0,0,0,0,0,0]]
- Output:
- 4
- Explanation:
The group in the upper left touches the top edge, so its cells can walk off. The 2 by 2 block is closed in by sea, so its four cells are landlocked and the answer is 4.
Example 2
- Input:
- grid = [[0,0,0,0,0],[0,1,1,1,0],[0,1,1,1,0],[0,1,1,1,0],[0,0,0,0,0]]
- Output:
- 9
- Explanation:
The 3 by 3 block of land never touches the edge, so all 9 cells are landlocked.
Example 3
- Input:
- grid = [[0,1,0,0],[0,1,1,0],[0,0,1,0]]
- Output:
- 0
- Explanation:
The land cell on the top edge is connected to all the others, so every land cell can walk off and the answer is 0.
Constraints
1 ≤ R, C ≤ 400
grid[i][j] is 0 or 1
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(R * C)
- Space
- O(R * C)