Given a 2d grid map of '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
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
思路:这题可以用BFS和DFS来做,注意x, y要判断是否visited过,才进入循环;
错误点:没有判断grid[x][y] == '1';
class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
boolean[][] visited = new boolean [m][n];
int count = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(!visited[i][j] && grid[i][j] == '1') {
count++;
// bfs(grid, i, j, visited);
dfs(grid, i, j, visited);
}
}
}
return count;
}
private int[][] dirs = {{0,1},{0,-1}, {1,0}, {-1,0}};
private void dfs(char[][] grid, int x, int y, boolean[][] visited) {
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || visited[x][y]) {
return;
}
if(grid[x][y] == '1') {
visited[x][y] = true;
for(int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
dfs(grid, nx, ny, visited);
}
}
}
private void bfs(char[][] grid, int x, int y, boolean[][] visited) {
Queue<int[]> queue = new LinkedList<>();
int m = grid.length;
int n = grid[0].length;
int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
queue.offer(new int[] {x, y});
visited[x][y] = true;
while(!queue.isEmpty()) {
int[] node = queue.poll();
int nodex = node[0];
int nodey = node[1];
for(int[] dir: dirs) {
int nx = nodex + dir[0];
int ny = nodey + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n && !visited[nx][ny] && grid[nx][ny] == '1') {
queue.offer(new int[] {nx, ny});
visited[nx][ny] = true;
}
}
}
}
}
这题还可以用union find做:
class Solution {
public class UnionFind {
public int[] father;
public int count;
public UnionFind (char[][] grid) {
int m = grid.length;
int n = grid[0].length;
this.father = new int[m * n];
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '1') {
count++;
father[i * n + j] = i * n + j; // 注意是乘以col n;
}
}
}
}
public int find(int x) {
int j = x;
while(father[j] != j) {
j = father[j];
}
// path compression;
while(x != j) {
int fx = father[x];
father[x] = j;
x = fx;
}
return j;
}
public void union(int a, int b) {
int root_a = find(a);
int root_b = find(b);
if(root_a != root_b) {
father[root_a] = root_b;
count--;
}
}
}
private int[][] dirs = {{0,1},{0,-1},{-1,0},{1,0}};
public int numIslands(char[][] grid) {
UnionFind uf = new UnionFind(grid);
int m = grid.length;
int n = grid[0].length;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '1') {
for(int[] dir: dirs) {
int nx = i + dir[0];
int ny = j + dir[1];
if(0 <= nx && nx < m && 0 <= ny && ny < n && grid[nx][ny] == '1') {
uf.union(i * n + j, nx * n + ny);
}
}
}
}
}
return uf.count;
}
}