题目
Given a 2d grid map of 1s (land) and 0s (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
解题思路
遍历整个数组,并建立一个2D boolean array标记check过的元素, 每次遇到未标记的‘1’时,用Breadth First Search标记所有相连的‘1’,即island
Time Complexity: O(n) = n * m
Space Complexity: O(n) = n * m
public class Solution {
class Cell {
int x;
int y;
public Cell(int x, int y) {
this.x = x;
this.y = y;
}
}
public int numIslands(char[][] grid) {
// Write your solution here
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int n = grid.length, m = grid[0].length;
boolean[][] visited = new boolean[n][m];
int count = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == '1' && !visited[i][j]) {
mark(grid, visited, i, j);
count++;
}
}
}
return count;
}
private void mark(char[][] grid, boolean[][] visited, int x, int y) {
Queue<Cell> q = new ArrayDeque<>();
q.offer(new Cell(x, y));
visited[x][y] = true;
while (!q.isEmpty()) {
Cell curr = q.poll();
if (curr.x-1 >= 0 && !visited[curr.x-1][curr.y] && grid[curr.x-1][curr.y] == '1') {
q.offer(new Cell(curr.x-1, curr.y));
visited[curr.x-1][curr.y] = true;
}
if (curr.y-1 >= 0 && !visited[curr.x][curr.y-1] && grid[curr.x][curr.y-1] == '1') {
q.offer(new Cell(curr.x, curr.y-1));
visited[curr.x][curr.y-1] = true;
}
if (curr.x+1 <grid.length && !visited[curr.x+1][curr.y] && grid[curr.x+1][curr.y] == '1') {
q.offer(new Cell(curr.x+1, curr.y));
visited[curr.x+1][curr.y] = true;
}
if (curr.y+1 < grid[0].length && !visited[curr.x][curr.y+1] && grid[curr.x][curr.y+1] == '1') {
q.offer(new Cell(curr.x, curr.y+1));
visited[curr.x][curr.y+1] = true;
}
}
}
}