200. Number of Islands
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
解法一
bfs, 宽度优先搜索,判断能够有几个bfs,就有几个岛屿。
class Solution {
class Coordinate {
int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
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;
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
bfs(i, j, grid);
count++;
}
}
}
return count;
}
public void bfs(int i, int j, char[][] grid) {
Queue<Coordinate> queue = new LinkedList<>();
Coordinate root = new Coordinate(i, j);
grid[i][j] = '0';
queue.offer(root);
int[] directionX = {0, -1, 0, 1};
int[] directionY = {-1, 0, 1, 0};
while (!queue.isEmpty()) {
Coordinate coor = queue.poll();
for (int k = 0; k < 4; k++) {
Coordinate adj = new Coordinate(coor.x + directionX[k], coor.y + directionY[k]);
if (outBound(adj, grid)) {
continue;
}
if (grid[adj.x][adj.y] == '1') {
grid[adj.x][adj.y] = '0';
queue.offer(adj);
}
}
}
}
public boolean outBound(Coordinate coordinate, char[][] grid) {
if (coordinate.x < 0 || coordinate.x >= grid.length || coordinate.y < 0 || coordinate.y >= grid[0].length) {
return true;
}
return false;
}
}