'1'
s (land) and '0'
s
(water), count the number of islands. An island is surrounded by water
and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.Example 1:
11110 11010 11000 00000Answer: 1
Example 2:
11000 11000 00100 00011Answer: 3
Naive Way: Use DFS to go though all grid cells. Use a hashset to keep visited grid cells. Run time is O(n^2). And space is O(n^2).
public class Solution {
public int numIslands(char[][] grid) {
Set<List<Integer>> visited = new HashSet<List<Integer>>();
int num = 0;
for(int i = 0;i < grid.length;i++)
for(int j = 0;j < grid[0].length;j++)
num+=dfs(grid,i,j,visited);
return num;
}
private int dfs(char[][] grid, int x, int y, Set<List<Integer>> visited){
// edge case
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length) return 0;
// island
if(grid[x][y] == '1'){
List<Integer> list = new ArrayList<Integer>();
list.add(x);
list.add(y);
if(!visited.contains(list)){
visited.add(list);
dfs(grid, x-1, y, visited);
dfs(grid, x+1, y, visited);
dfs(grid, x, y-1, visited);
dfs(grid, x, y+1, visited);
return 1;
}
}
return 0;
}
}
I saw a algorithm in Discuss use the original grid to store visited grid cells. Thus reduce space used to O(1).
No comments:
Post a Comment