public int minDistanceToIsland(int[][] grid, int rowIndex, int colIndex) {
if (grid.length == 0) return -1;
int m = grid.length;
int n = grid[0].length;
int distance = 0;
int[][] next = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
Queue<int[]> queue = new ArrayDeque<>();
queue.offer(new int[]{rowIndex, colIndex});
grid[rowIndex][colIndex] = 2;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] curr = queue.poll();
for (int j = 0; j < next.length; j++) {
int nextR = curr[0] + next[j][0];
int nextC = curr[1] + next[j][1];
if (nextR < 0 || nextR >= m || nextC < 0 || nextC >= n || grid[nextR][nextC] == 2) continue;
if (grid[nextR][nextC] == 1) return distance + 1;
queue.offer(new int[]{nextR, nextC});
grid[nextR][nextC] = 2;
}
}
distance++;
}
return -1;
}
public int minDistanceToIsland(int[][] grid, int i, int j) {
int m = grid.length;
if (m == 0) return 0;
int n = grid[0].length;
if (i < 0 || i >= m || j < 0 || j >= n) return 0;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{i, j});
int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int depth = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int k = 0; k < size; k++) {
int[] cell = queue.poll();
if (grid[cell[0]][cell[1]] == 1) return depth;
grid[cell[0]][cell[1]] = 2;
for (int[] d : dirs) {
int r = cell[0] + d[0];
int c = cell[1] + d[1];
if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 2)
continue;
queue.offer(new int[]{r, c});
}
}
depth++;
}
return depth;
}
01表示岛屿和水的模型中,求与给定点最近的岛屿的距离
最新推荐文章于 2021-10-15 21:49:03 发布