Merge pull request #2725 from cyxiwai/kama99

更新并补充了kama0099.岛屿的数量dfs和bfs的版本,附有详细注释
This commit is contained in:
程序员Carl
2024-09-14 10:24:31 +08:00
committed by GitHub
2 changed files with 93 additions and 1 deletions

View File

@ -191,10 +191,57 @@ int main() {
### Java
```java
import java.util.*;
public class Main {
public static int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//下右上左逆时针遍历
public static void bfs(int[][] grid, boolean[][] visited, int x, int y) {
Queue<pair> queue = new LinkedList<pair>();//定义坐标队列没有现成的pair类在下面自定义了
queue.add(new pair(x, y));
visited[x][y] = true;//遇到入队直接标记为优先,
// 否则出队时才标记的话会导致重复访问,比如下方节点会在右下顺序的时候被第二次访问入队
while (!queue.isEmpty()) {
int curX = queue.peek().first;
int curY = queue.poll().second;//当前横纵坐标
for (int i = 0; i < 4; i++) {
//顺时针遍历新节点next下面记录坐标
int nextX = curX + dir[i][0];
int nextY = curY + dir[i][1];
if (nextX < 0 || nextX >= grid.length || nextY < 0 || nextY >= grid[0].length) {
continue;
}//去除越界部分
if (!visited[nextX][nextY] && grid[nextX][nextY] == 1) {
queue.add(new pair(nextX, nextY));
visited[nextX][nextY] = true;//逻辑同上
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int[][] grid = new int[m][n];
boolean[][] visited = new boolean[m][n];
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
grid[i][j] = sc.nextInt();
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (!visited[i][j] && grid[i][j] == 1) {
ans++;
bfs(grid, visited, i, j);
}
}
}
System.out.println(ans);
}
}
```

View File

@ -182,7 +182,52 @@ int main() {
## 其他语言版本
### Java
```java
import java.util.Scanner;
public class Main {
public static int[][] dir ={{0,1},{1,0},{-1,0},{0,-1}};
public static void dfs(boolean[][] visited,int x,int y ,int [][]grid)
{
for (int i = 0; i < 4; i++) {
int nextX=x+dir[i][0];
int nextY=y+dir[i][1];
if(nextY<0||nextX<0||nextX>= grid.length||nextY>=grid[0].length)
continue;
if(!visited[nextX][nextY]&&grid[nextX][nextY]==1)
{
visited[nextX][nextY]=true;
dfs(visited,nextX,nextY,grid);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m= sc.nextInt();
int n = sc.nextInt();
int[][] grid = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
grid[i][j]=sc.nextInt();
}
}
boolean[][]visited =new boolean[m][n];
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if(!visited[i][j]&&grid[i][j]==1)
{
ans++;
visited[i][j]=true;
dfs(visited,i,j,grid);
}
}
}
System.out.println(ans);
}
}
```
### Python
版本一