- [ ] ### 简单图上的搜索BFS(Queue,不分层
- [ ] ### 暂时可以不用再写了,一次AC
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
Credits:
Special thanks to@mithmattfor adding this problem and creating all test cases.
class Solution {
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int ans = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
markByBFS(grid, i, j);
ans++;
}
}
}
return ans;
}
public void markByBFS(char[][] grid, int x, int y) {
int[] dx = {1, -1, 0, 0};
int[] dy = {0, 0, 1, -1};
Queue<Coordinate> queue = new LinkedList<>();
Coordinate head = new Coordinate(x, y);
queue.offer(head);
while (!queue.isEmpty()) {
Coordinate node = queue.poll();
for (int i = 0; i < 4; i++) {
int newX = node.x + dx[i];
int newY = node.y + dy[i];
if ((!isValid(grid, newX, newY) )|| grid[newX][newY] == '0' ) {
continue;
}
Coordinate newNode = new Coordinate(newX, newY);
grid[newX][newY] = '0';
queue.offer(newNode);
}
}
}
public boolean isValid(char[][] grid, int x, int y) {
int m = grid.length;
int n = grid[0].length;
return x>=0 && x< m && y >= 0 && y < n;
}
private class Coordinate {
int x;
int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
}