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