Count the Stranded Land Tiles
Implement countStranded
You are given a grid of land (1) and sea (0). From a land tile you may walk to a neighbouring land tile (up, down, left or right), and from a land tile on the border of the grid you may walk off the grid. Count the land tiles from which it is impossible to leave the grid.
Instead of testing every tile, start from the border: everything connected to border land can leave the grid, and whatever is left over is stranded.
Example 1:
Input: grid = [[0,0,0,0,1],[1,1,0,0,0],[0,1,0,1,0],[0,0,1,1,0],[0,0,0,0,0]]
Output: 3
Example 2:
Input: grid = [[1,1],[1,1]]
Output: 0
Example 3:
Input: grid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 1
+ 12 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ rows, cols ≤ 12; grid[r][c] is 1 (land) or 0 (sea) - ●
A move goes from a land tile to a neighbouring land tile (up, down, left, right), or off the grid from a land tile on the border - ●
A land tile is stranded when NO sequence of such moves can leave the grid - ●
Return the number of stranded land tiles
grid =
[[0,0,0,0,1], [1,1,0,0,0], [0,1,0,1,0], [0,0,1,1,0], [0,0,0,0,0]]