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
class Solution {
public int shortestBridge(int[][] A) {
int m = A.length, n = A[0].length;
Queue<int[]> queue = new LinkedList();
boolean[][] visited = new boolean[m][n];
int[][] directions = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
boolean found = false;
for (int i = 0; i < m && !found; i++) {
for (int j = 0; j < n && !found; j++) {
if (A[i][j] == 1) {
findIslandByDFS(i, j, queue, visited, directions, A);
found = true;
break;
}
}
}
int step = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size-- > 0) {
int[] cur = queue.remove();
for (int[] direction : directions) {
int nextRow = cur[0] + direction[0];
int nextCol = cur[1] + direction[1];
if (nextRow >= 0 && nextCol >= 0 && nextRow < m && nextCol < n && !visited[nextRow][nextCol]) {
if (A[nextRow][nextCol] == 1) {
return step;
}
queue.add(new int[] {nextRow, nextCol});
visited[nextRow][nextCol] = true;
}
}
}
++step;
}
return step;
}
public void findIslandByDFS(int row, int col, Queue<int[]> queue, boolean[][] visited, int[][] directions, int[][] A) {
if (row < 0 || col < 0 || row >= A.length || col >= A[0].length || A[row][col] == 0 || visited[row][col]) {
return;
}
visited[row][col] = true;
queue.add(new int[] {row, col});
for (int[] direction : directions) {
int nextRow = row + direction[0];
int nextCol = col + direction[1];
findIslandByDFS(nextRow, nextCol, queue, visited, directions, A);
}
}
}
3. Time & Space Complexity