Skip to content
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
81 changes: 41 additions & 40 deletions problems/kamacoder/0101.孤岛的总面积.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,69 +189,70 @@ int main() {
import java.util.*;

public class Main {
private static int count = 0;
private static final int[][] dir = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; // 四个方向

private static void bfs(int[][] grid, int x, int y) {
Queue<int[]> que = new LinkedList<>();
que.add(new int[]{x, y});
grid[x][y] = 0; // 只要加入队列,立刻标记
count++;
while (!que.isEmpty()) {
int[] cur = que.poll();
int curx = cur[0];
int cury = cur[1];
static int area = 0;
static int[][] directions = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };

// BFS:从(x,y)出发,将所有与之相连的陆地标记为0(消除)
public static void bfs(int[][] graph, int x, int y) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[] { x, y });
graph[x][y] = 0; // 入队立刻标记,避免重复访问
while (!queue.isEmpty()) {
int[] cur = queue.poll();
int curX = cur[0];
int curY = cur[1];
for (int i = 0; i < 4; i++) {
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 (grid[nextx][nexty] == 1) {
que.add(new int[]{nextx, nexty});
count++;
grid[nextx][nexty] = 0; // 只要加入队列立刻标记
int nextX = curX + directions[i][0];
int nextY = curY + directions[i][1];
// 越界跳过
if (nextX < 0 || nextX >= graph.length || nextY < 0 || nextY >= graph[0].length) {
continue;
}
if (graph[nextX][nextY] == 1) {
queue.add(new int[] { nextX, nextY });
graph[nextX][nextY] = 0; // 入队立刻标记
}
}
}
}

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

// 读取网格
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int[][] graph = new int[n][m];

for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
grid[i][j] = scanner.nextInt();
graph[i][j] = sc.nextInt();
}
}

// 从左侧边,和右侧边向中间遍历

// 第一阶段:从四条边出发,消除所有与边缘相连的陆地
// 这些陆地不是孤岛,直接标记为0
for (int i = 0; i < n; i++) {
if (grid[i][0] == 1) bfs(grid, i, 0);
if (grid[i][m - 1] == 1) bfs(grid, i, m - 1);
if (graph[i][0] == 1) bfs(graph, i, 0); // 左边
if (graph[i][m - 1] == 1) bfs(graph, i, m - 1); // 右边
}

// 从上边和下边向中间遍历
for (int j = 0; j < m; j++) {
if (grid[0][j] == 1) bfs(grid, 0, j);
if (grid[n - 1][j] == 1) bfs(grid, n - 1, j);
for (int i = 0; i < m; i++) {
if (graph[0][i] == 1) bfs(graph, 0, i); // 上边
if (graph[n - 1][i] == 1) bfs(graph, n - 1, i); // 下边
}
count = 0;

// 第二阶段:统计剩余陆地面积,即孤岛总面积
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (grid[i][j] == 1) bfs(grid, i, j);
if (graph[i][j] == 1) {
area++;
}
}
}

System.out.println(count);
System.out.println(area);
}
}



```


Expand Down