代码拉取完成,页面将自动刷新
package LeetCode;
import java.util.*;
public class LC_200v2 {
static int[][] move = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
static Deque<int[]> que = new ArrayDeque<>();
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', '1', '1'}};
System.out.println(numIslands(grid));
}
public static int numIslands(char[][] grid) {
boolean[][] visited = new boolean[grid.length][grid[0].length];
//Arrays.fill(visited, false);
int res = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (!visited[i][j] && grid[i][j] == '1') {
que.add(new int[]{i, j});
bfs(grid, visited);
res++;
}
}
}
return res;
}
public static void bfs(char[][] grid, boolean[][] visited) {
while (!que.isEmpty()) {
int x = que.getFirst()[0];
int y = que.getFirst()[1];
que.removeFirst();
for (int i = 0; i < move.length; i++) {
int next_X = x + move[i][0];
int next_Y = y + move[i][1];
if (next_X < 0 || next_X >= grid.length || next_Y < 0 || next_Y >= grid[0].length) continue;
else {
if (!visited[next_X][next_Y] && grid[next_X][next_Y] == '1') {
que.add(new int[]{next_X, next_Y});
visited[next_X][next_Y] = true;
}
}
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。