1 Star 0 Fork 0

Neo_1001/LeetCode刷题记录

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
LC_200.java 1.77 KB
一键复制 编辑 原始数据 按行查看 历史
Neo_1001 提交于 2024-04-10 22:16 . first commit
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;
}
}
}
}
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/neo1001/leet-code-practice-record.git
git@gitee.com:neo1001/leet-code-practice-record.git
neo1001
leet-code-practice-record
LeetCode刷题记录
master

搜索帮助