题目来源:https://leetcode-cn.com/problems/number-of-enclaves/
大致题意:
给一个矩阵网格,元素由 1 和 0 组成,其中 1 表示陆地, 0 表示水域,求出不在边缘的且周围只有水域的陆地个数
思路
可以使用多源最短路径来解题,出发点为边缘的所有陆地点,然后搜索内部的陆地点,最后未被搜索到的陆地就是所求数目
多源最短路径
- 遍历网格,统计内部的陆地个数 count,并将边缘的陆地作为起点放入队列中
- BFS 内部陆地,每寻找到一个,将之前统计的陆地个数 count 减 1
- BFS 结束后,此时的 count 即为所求
代码:
public int numEnclaves(int[][] grid) {
Queue<int[]> queue = new ArrayDeque<>();
int[] direction = new int[]{1, 0, -1, 0, 1};
int landCount = 0;
int m = grid.length;
int n = grid[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
// 若为水域,直接跳过
if (grid[i][j] == 0) {
continue;
}
// 若为边缘陆地,放入队列
if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {
queue.offer(new int[]{i, j});
// 已搜索的陆地置 0,防止重复搜索
grid[i][j] = 0;
} else {
// 统计内部陆地数
landCount++;
}
}
}
// BFS
while (!queue.isEmpty()) {
int[] coordinate = queue.poll();
int x = coordinate[0];
int y = coordinate[1];
for (int i = 0; i < 4; i++) {
int newX = x + direction[i];
int newY = y + direction[i + 1];
if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] != 0) {
// 更新未搜索的陆地(即内部陆地)数目
landCount--;
queue.offer(new int[]{newX, newY});
// 已搜索的陆地置 0,防止重复搜索
grid[newX][newY] = 0;
}
}
}
return landCount;
}