Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

添加 0101.孤岛的总面积.md Java版本 #2966

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Mirwangjn wants to merge 1 commit into youngyangyang04:master
base: master
Choose a base branch
Loading
from Mirwangjn:master
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 70 additions & 3 deletions problems/kamacoder/0101.孤岛的总面积.md
View file Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,78 @@ int main() {

### Java

#### 深搜版
``` java
import java.util.*;

public class Main {
//接收矩阵所用到的图
public static int[][] grid;
//遍历上下左右四个方向的数组
public static int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
//最终结果
public static int result = 0;

public static void dfs(int x, int y) {
//将陆地变为海洋
grid[x][y] = 0;

for (int i = 0; i < 4; i++) {
//下一个x坐标
int nextX = x + direction[i][0];
//下一个y坐标
int nextY = y + direction[i][1];
//确保坐标位置访问不会越界
if (nextX < 0 || nextX >= grid.length || nextY < 0 || nextY >= grid[0].length) continue;
//如果下一个坐标位置是陆地, 则继续递归将周围的陆地变为海洋
if (grid[nextX][nextY] == 1) {
dfs(nextX, nextY);
}
}
}

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();

grid = new int[n][m];

//填充grid图
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
grid[i][j] = sc.nextInt();
}
}
//遍历行方向的两条边
for (int i = 0; i < n; i++) {
//如果是岛屿则将当前岛屿以及周围的岛屿都变为海洋
if (grid[i][0] == 1) dfs(i, 0);

if (grid[i][m - 1] == 1) dfs(i, m - 1);
}
//遍历列方向的两条边
for (int j = 0; j < m; j++) {
if (grid[0][j] == 1) dfs(0, j);

if (grid[n - 1][j] == 1) dfs(n - 1, j);
}
//遍历累加结果
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) {
result++;
}
}
}
//打印结果
System.out.println(result);
}
}
```

#### 广搜版
``` java
import java.util.*;

public class Main {
Expand Down Expand Up @@ -249,9 +319,6 @@ public class Main {
System.out.println(count);
}
}



```


Expand Down

AltStyle によって変換されたページ (->オリジナル) /