1. 程式人生 > >[LeetCode] 935. Knight Dialer

[LeetCode] 935. Knight Dialer

題:https://leetcode.com/problems/shortest-bridge/description/

題目

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: 1

Example 2:

Input: [[0,1,0],[0,0,0],[0,0,1]]
Output: 2

Example 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. 1 <= A.length = A[0].length <= 100
  2. A[i][j] == 0 or A[i][j] == 1

題目大意

給定二維陣列A中,有兩個島(每個島由1組成,被0保衛)

現在,我們將0變為1,以使 兩島 連線起來,成為一個島。

求翻轉 0 的最小數目。

思路

首先,選一個島,然後dfs膨脹,將該島的1變為-1。將島的每個座標放入 佇列queue中。用queue 進行 bfs ,若元素為0,那麼繼續放入queue 遍歷,放入queue的點都 置為-1;若元素為1,則已遍歷到另個島。

class Solution {
    int[][] directions = {{-1,0},{1,0},{0,-1},{0,1}};
    Queue<int[]> queue = new LinkedList<>();

    public
void dfsf(int[][] A,int r,int l,int rlen,int llen){ if(!(r>=0 && r<rlen && l>=0 && l<llen && A[r][l]==1) ) return; A[r][l] = -1; queue.offer(new int[]{r,l}); for(int [] direction:directions){ dfsf(A,r+direction[0],l+direction[1],rlen,llen); } } public int shortestBridge(int[][] A) { boolean flag = true; for (int i = 0; i < A.length && flag; i++) for (int j = 0; j < A[0].length && flag; j++) if (A[i][j] == 1) { dfsf(A, i,j ,A.length,A[0].length); flag = false; break; } int level = 0; while(!queue.isEmpty()){ int queueSize = queue.size(); level++; while (queueSize-->0){ int[] cur = queue.poll(); for(int [] direction:directions){ int tr = cur[0] + direction[0]; int tl = cur[1] + direction[1]; if(!(tr>=0 && tr<A.length && tl>=0 && tl< A[0].length)) continue; if(A[tr][tl]==1) return level-1; else if(A[tr][tl]==0){ queue.offer(new int[]{tr,tl}); A[tr][tl] = -1; } } } } return -1; } }