[LeetCode] 934. Shortest Bridge
2409 단어 union-finddfsbfs자바
In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of 1s not connected to any other 1s.)
Now, we may change 0s to 1s so as to connect the two islands together to form 1 island.
Return the smallest number of 0s that must be flipped. (It is guaranteed that the answer is at least 1.)
Example 1:
Input: [[0,1],[1,0]]Output: 1Example 2:
Input: [[0,1,0],[0,0,0],[0,0,1]]Output: 2Example 3:
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
Note:
1 <= A.length = A[0].length <= 100Ai == 0 or Ai == 1
Solution
class Solution {
public int shortestBridge(int[][] A) {
//find the first island, using dfs
int m = A.length, n = A[0].length;
boolean[][] visited = new boolean[m][n];
Queue queue = new LinkedList<>(); //for bfs
int[][] dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}};
boolean found = false;
for (int i = 0; i < m; i++) {
if (found) break;
for (int j = 0; j < n; j++) {
if (A[i][j] == 1) {
found = true;
dfs(A, i, j, visited, dirs, queue);
break;
}
}
}
int count = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
int[] cur = queue.poll();
for (int[] dir: dirs) {
int x = cur[0]+dir[0], y = cur[1]+dir[1];
if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y]) continue;
if (A[x][y] == 1) return count;
queue.offer(new int[]{x, y});
visited[x][y] = true;
}
}
count++;
}
return -1;
}
private void dfs(int[][] A, int i, int j, boolean[][] visited, int[][] dirs, Queue queue) {
int m = A.length, n = A[0].length;
if (i < 0 || i >= m || j < 0 || j >= n || A[i][j] == 0 || visited[i][j]) return;
queue.offer(new int[]{i, j});
visited[i][j] = true;
for (int[] dir: dirs) {
dfs(A, i+dir[0], j+dir[1], visited, dirs, queue);
}
}
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[LeetCode] 934. Shortest BridgeProblem In a given 2D binary array A, there are two islands. (An island is a 4-directionally connected group of 1s not c...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.