Merge pull request #2776 from jjblaack/master

100.岛屿的最大面积 添加了java实现(dfs+bfs两种方法)
This commit is contained in:
程序员Carl
2024-10-21 09:25:27 +08:00
committed by GitHub

View File

@ -223,7 +223,121 @@ public:
## 其他语言版本 ## 其他语言版本
### Java ### Java
DFS
```java
//这里的实现为主函数处理每个岛屿的第一块陆地 方式
//所以是主函数直接置count为1剩余的交给dfs来做。
import java.util.*;
public class Main{
static int[][] dir = {{0,-1}, {1,0}, {0,1}, {-1, 0}};//四个方向
static int count = 0;
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(nextX < 0 || nextY < 0 || nextY >= grid[0].length || nextX >= grid.length){
continue;
}
if(!visited[nextX][nextY] && grid[nextX][nextY] == 1){
count++;
visited[nextX][nextY] = true;
dfs(visited, nextX, nextY, grid);
}
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[][] grid = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
grid[i][j] = in.nextInt();
}
}
int result = 0;
boolean[][] visited = new boolean[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(!visited[i][j] && grid[i][j] == 1){
visited[i][j] = true;
count = 1;
dfs(visited, i, j, grid);
//dfs遍历完了一座岛屿就比较count和result保留最大的
result = Math.max(result, count);
}
}
}
System.out.println(result);
}
}
```
BFS
```java
import java.util.*;
public class Main{
static int[][] dir = {{0,-1}, {1,0}, {0,1}, {-1, 0}};//下右上左的顺序
static int count = 0;
public static void bfs(boolean[][] visited, int x, int y, int[][] grid){
Queue<pair> queue = new LinkedList<pair>();
queue.add(new pair(x,y));
count = 1; //该岛屿的第一块陆地被visit了
//对这个岛屿的所有都入队,除非上下左右都没有未访问的陆地
while(!queue.isEmpty()){
int curX = queue.peek().x;
int curY = queue.poll().y;
//对每块陆地都进行上下左右的入队和计算(遍历),自然就是按广度优先了
for(int i = 0; i < 4; i++){
int nextX = curX + dir[i][0];
int nextY = curY + dir[i][1];
if(nextX < 0 || nextY < 0 || nextX >= grid.length || nextY >= grid[0].length){
continue;
}
if(!visited[nextX][nextY] && grid[nextX][nextY] == 1){
count++;
queue.add(new pair(nextX, nextY));
visited[nextX][nextY] = true;
}
}
}
}
static class pair{
int x;
int y;
pair(int x, int y){
this.x = x;
this.y = y;
}
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
int[][] grid = new int[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
grid[i][j] = in.nextInt();
}
}
int result = 0;
boolean[][] visited = new boolean[n][m];
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(!visited[i][j] && grid[i][j] == 1){
visited[i][j] = true;
bfs(visited, i, j, grid);
result = Math.max(result, count);
}
}
}
System.out.println(result);
}
}
```
### Python ### Python
DFS DFS