934. Shortest Bridge
Explanation
To solve this problem, we can follow these steps:
- Use depth-first search (DFS) to label the two islands separately with different numbers.
- Use breadth-first search (BFS) to expand from one island towards the other, keeping track of the number of flips needed to connect the two islands.
- Stop the BFS when we reach the other island, and return the number of flips needed.
Time complexity: O(n^2)
Space complexity: O(n^2)
class Solution {
public int shortestBridge(int[][] grid) {
int n = grid.length;
boolean[][] visited = new boolean[n][n];
Queue<int[]> queue = new LinkedList<>();
boolean found = false;
// DFS to label the two islands with different numbers
for (int i = 0; i < n; i++) {
if (found) break;
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1) {
dfs(grid, i, j, visited, queue);
found = true;
break;
}
}
}
int steps = 0;
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
// BFS to expand from one island towards the other
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] curr = queue.poll();
for (int[] dir : directions) {
int x = curr[0] + dir[0];
int y = curr[1] + dir[1];
if (x >= 0 && x < n && y >= 0 && y < n && !visited[x][y]) {
if (grid[x][y] == 1) {
return steps;
}
visited[x][y] = true;
queue.offer(new int[]{x, y});
}
}
}
steps++;
}
return -1;
}
private void dfs(int[][] grid, int i, int j, boolean[][] visited, Queue<int[]> queue) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || visited[i][j] || grid[i][j] == 0) {
return;
}
visited[i][j] = true;
queue.offer(new int[]{i, j});
dfs(grid, i + 1, j, visited, queue);
dfs(grid, i - 1, j, visited, queue);
dfs(grid, i, j + 1, visited, queue);
dfs(grid, i, j - 1, visited, queue);
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.