Given a matrix, find the perimeter of the connected grid land
Intuition
Use DFS to find the island, then compute the perimeter.
Approach
We use result
to store the result and find all connected components of the island with DFS, to compute the perimeter,
to update result
, we need to compute how many components that are connected the current component.
Now, note that to prevent infinite recursion, we set grid[i][j] = -1
to mark it visited, then for each component, it may be in three states:
grid[i][j] = 0
, it is watergrid[i][j] = 1
, it is a component of the island and being unvisitedgrid[i][j] = -1
, it is a component of the island and has been visited.
Complexity
Time complexity: iterate all grids once. $$O(mn)$$
Space complexity: no extra space needed $$O(1)$$
Code
|
|