In a given 2D binary array A
, there are two islands. (An island is a 4-directionally connected group of 1
s not connected to any other 1s.)
Now, we may change 0
s to 1
s so as to connect the two islands together to form 1 island.
Return the smallest number of 0
s that must be flipped. (It is guaranteed that the answer is at least 1.)
Example 1:
Input: A = [[0,1],[1,0]] Output: 1
Example 2:
Input: A = [[0,1,0],[0,0,0],[0,0,1]] Output: 2
Example 3:
Input: A = [[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
Constraints:
2 <= A.length == A[0].length <= 100
A[i][j] == 0
orA[i][j] == 1
思路:很简单,就是先找到第一个island,然后做bfs,这里注意的是:找第一个island不能用bfs,因为queue是poll完全出来了,queue的size是0了,只能用dfs来找,找到了populate queue了,然后再用bfs来找step;找第一个island的时候,也需要注意,找到的第一个1的点,就需要break,而且break要break两次;外层循环也需要break;
注意:找到第一个component,需要break两层循环,也就是break掉两个地方;
class Solution {
public int shortestBridge(int[][] grid) {
int n = grid.length;
boolean[][] visited = new boolean[n][n];
Queue<int[]> queue = new LinkedList<>();
boolean findone = false;
for(int i = 0; i < n; i++) {
if(findone) break;
for(int j = 0; j < n; j++) {
if(grid[i][j] == 1) {
dfs(queue, grid, i, j, visited);
findone = true;
break;
}
}
}
int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};
int step = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
int[] node = queue.poll();
int x = node[0];
int y = node[1];
for(int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if(0 <= nx && nx < n && 0 <= ny && ny < n && !visited[nx][ny]) {
if(grid[nx][ny] == 1) {
return step;
}
queue.offer(new int[]{nx, ny});
visited[nx][ny] = true;
}
}
}
step++;
}
return -1;
}
private int[][] dirs = new int[][]{{0,1},{0,-1},{-1,0},{1,0}};
private void dfs(Queue<int[]> queue, int[][] grid, int x, int y, boolean[][] visited) {
if(x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || visited[x][y]) {
return;
}
if(grid[x][y] == 1) {
queue.offer(new int[]{x, y});
visited[x][y] = true;
for(int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
dfs(queue, grid, nx, ny, visited);
}
}
}
}