[Vssue]kamacoder/0102.沉没孤岛.md
Opened this issue · 1 comments
// java版本
// 标记方式为将1变为2,最后在输出前再将2变为1
import java.util.Scanner;
public class Main {
public static final int[][] dir = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] grid = new int[n][m];
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) {
grid[i][0] = 2;
dfs(grid, i, 0, 2);
}
if (grid[i][m - 1] == 1) {
grid[i][m - 1] = 2;
dfs(grid, i, m - 1, 2);
}
}
for (int j = 1; j < m - 1; j++) {
if (grid[0][j] == 1) {
grid[0][j] = 2;
dfs(grid, 0, j, 2);
}
if (grid[n - 1][j] == 1) {
grid[n - 1][j] = 2;
dfs(grid, n - 1, j, 2);
}
}
for (int i = 1; i < n - 1; i++) {
for (int j = 1; j < m - 1; j++) {
if (grid[i][j] == 1) {
grid[i][j] = 0;
dfs(grid, i, j, 0);
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 2) {
grid[i][j] = 1;
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m - 1; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println(grid[i][m - 1]);
}
}
public static void dfs(int[][] grid, int x, int y, int key) {
for (int i = 0; i < 4; i++) {
int nextX = x + dir[i][0];
int nextY = y + dir[i][1];
if (nextX >= 0 && nextY >= 0 && nextX < grid.length && nextY < grid[0].length && grid[nextX][nextY] == 1) {
grid[nextX][nextY] = key;
dfs(grid, nextX, nextY, key);
}
}
}
}