Input: [[0,1],[1,0]]
Output: 1
Input: [[0,1,0],[0,0,0],[0,0,1]]
Output: 2
Input: [[1,1,1,1,1],[1,0,0,0,1],[1,0,1,0,1],[1,0,0,0,1],[1,1,1,1,1]]
Output: 1
代码中利用一个found来做是否做完dfs的标示,然后岛1加入队列,向岛2扩张,找到2就结束输出level,是0就加入队列下一层去找,需要跳过是1的情况,是为了可以保证寻找到边缘的点
class Solution {
final int[][] DIR = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
public int shortestBridge(int[][] matrix) {
boolean found = false;
Queue<int[]> q = new LinkedList<>();
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] == 1 && !found) {
dfs(i, j, matrix);
found = true;
}
if (matrix[i][j] == 1 && found) {
q.offer(new int[]{i, j});
}
}
}
int level = 0;
while (!q.isEmpty()) {
int size = q.size();
while (size-- > 0) {
int[] curr = q.poll();
for (int[] dir : DIR) {
int x = curr[0] + dir[0];
int y = curr[1] + dir[1];
if (!isValid(x, y, matrix)) {
continue;
}
if (matrix[x][y] == 2) {
return level;
} else if (matrix[x][y] == 1) {
continue;
} else if (matrix[x][y] == 0) {
matrix[x][y] = 1;
q.offer(new int[]{x, y});
}
}
}
level++;
}
throw new IllegalArgumentException();
}
private void dfs(int x, int y, int[][] matrix) {
if (!isValid(x, y, matrix)) {
return;
}
if (matrix[x][y] != 1) {
return;
}
matrix[x][y] = 2;
for (int[] dir : DIR) {
dfs(x + dir[0], y + dir[1], matrix);
}
}
private boolean isValid(int x, int y, int[][] matrix) {
return 0 <= x && x < matrix.length && 0 <= y && y < matrix[0].length;
}
}