思路:
先遍历找到1,然后用bfs找到所有相连的1,并置成0,这一次遍历就是找到了一个岛屿。
代码:
import java.util.LinkedList;
import java.util.Queue;
public class Slution {
public static void main(String[] args) {
// char[][] grid = new char[][] {
// {'1','1','1','1','0'},
// {'1','1','0','1','0'},
// {'1','1','0','0','0'},
// {'0','0','0','0','0'}
// };
// char[][] grid = new char[][] {
// {'1','1','0','0','0'},
// {'1','1','0','0','0'},
// {'0','0','1','0','0'},
// {'0','0','0','1','1'}
// };
char[][] grid = new char[][]{
{'0','1'},
{'1','0'}
};
System.out.println(numIslands(grid));
}
public static int numIslands(char[][] grid) {
int sum = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == '1') {
bfs(grid, new Point(i,j));
sum++;
}
}
}
return sum;
}
public static void bfs(char[][] grid, Point start) {
Queue<Point> queue = new LinkedList<>();
queue.offer(start);
while (!queue.isEmpty()) {
Point point = queue.remove();
grid[point.x][ point.y] = '0';
if (point.x - 1 >= 0 && grid[point.x - 1][point.y] == '1') {
queue.add(new Point(point.x-1, point.y));
grid[point.x-1][point.y] = 0;
}
if (point.x + 1 < grid.length && grid[point.x + 1][point.y] == '1') {
queue.add(new Point(point.x+1, point.y));
grid[point.x+1][point.y] = 0;
}
if (point.y - 1 >= 0 && grid[point.x][point.y - 1] == '1') {
queue.add(new Point(point.x, point.y - 1));
grid[point.x][point.y-1] = 0;
}
if (point.y + 1 < grid[0].length && grid[point.x][point.y + 1] == '1') {
queue.add(new Point(point.x, point.y + 1));
grid[point.x][point.y+1] = 0;
}
}
}
public static class Point {
int x;
int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
}
Q.E.D.