LeetCode算法題-Flood Fill(Java實現)

這是悅樂書的第306次更新,第325篇原創 <br/>算法

01 看題和準備

今天介紹的是LeetCode算法題中Easy級別的第173題(順位題號是733)。圖像由二維整數數組表示,每一個整數表示圖像的像素值(從0到65535)。給定表示泛洪填充的起始像素(行和列)的座標(sr,sc)和像素值newColor,進行「泛洪填充」圖像。數組

要執行「泛洪填充」,請考慮起始像素,以及與起始像素相同顏色的起始像素4向鏈接的任何像素,以及與這些像素4向相連的任何像素(也使用與起始像素),依此類推。用newColor替換全部上述像素的顏色。最後,返回修改後的圖像。例如:數據結構

輸入:image = [[1,1,1],[1,1,0],[1,0,1]]eclipse

sr = 1,sc = 1,newColor = 2工具

輸出:[[2,2,2],[2,2,0],[2,0,1]]開發工具

說明:從圖像的中心(位置(sr,sc)=(1,1)),鏈接全部像素經過與起始像素相同顏色的路徑用新顏色着色。 <br/> 注意:測試

  • 圖像和圖像[0]的長度將在[1,50]範圍內。spa

  • 給定的起始像素將知足0 <= sr <image.length和0 <= sc <image [0] .length。code

  • image [i] [j]和newColor中每種顏色的值將是[0,65535]中的整數。遞歸

本次解題使用的開發工具是eclipse,jdk使用的版本是1.8,環境是win7 64位系統,使用Java語言編寫和測試。 <br/>

02 第一種解法

題目的意思是將起始位置的值改成新的值,若是值不相同的話。而且以起始座標開始,其上下左右四個方向的點,若是像素值和起始座標的相等,也要改成新的座標值,以這些四個方向上的點也會繼續向他們自己的四個方向延伸,直到不能修改成止。

上述問題的子問題與問題自己的性質同樣,都是以自己爲中心,向四個方向擴散,所以咱們能夠藉助遞歸來實現,可是須要注意邊界,不要下標越界了。

public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
    int oldColor = image[sr][sc];
    if (oldColor != newColor) {
        help(image, sr, sc, newColor, oldColor);
    }
    return image;
}

public void help(int[][] image, int sr, int sc, int newColor, int oldColor) {
    if (image[sr][sc] == oldColor) {
        image[sr][sc] = newColor;
        // 向上        
        if (sr-1 >= 0) {
            help(image, sr-1, sc, newColor, oldColor);
        }
        // 向下
        if (sr+1 < image.length) {
            help(image, sr+1, sc, newColor, oldColor);
        }
        // 向左
        if (sc-1 >= 0) {
            help(image, sr, sc-1, newColor, oldColor);
        }
        // 向右
        if (sc+1 < image[0].length) {
            help(image, sr, sc+1, newColor, oldColor);
        }
    }
}

<br/>

03 第二種解法

咱們也可使用迭代的方式來實現,藉助隊列。隊列中存放的是座標,以數組形式表現,另外將四個方向用兩個座標數組來表示,x表示行的方向,y表示列的方向。在隊列中判斷四個方向的數據是否符合要求,不能越界而且要等於原始起點的值,將知足這些條件的座標存入數組。

public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
    int oldColor = image[sr][sc];
    if (oldColor == newColor) {
        return image;
    }
    Queue<int[]> queue = new LinkedList<int[]>();
    queue.offer(new int[]{sr, sc});    
    int[] x = {1,-1,0,0};
    int[] y = {0,0,1,-1};
    while (!queue.isEmpty()) {
        int size = queue.size();
        for (int i=0; i<size; i++) {
            int[] temp = queue.poll();
            int m = temp[0];
            int n = temp[1];
            image[m][n] = newColor;
            for (int j=0; j<4; j++) {
                int nx = x[j]+m;
                int ny = y[j]+n;
                if (nx>=image.length || nx<0 || ny>=image[0].length || ny<0 || image[nx][ny] != oldColor) {
                    continue;
                }
                queue.offer(new int[]{nx, ny});
            }
        }
    }
    return image;
}

<br/>

04 小結

算法專題目前已日更超過五個月,算法題文章174+篇,公衆號對話框回覆【數據結構與算法】、【算法】、【數據結構】中的任一關鍵詞,獲取系列文章合集。

以上就是所有內容,若是你們有什麼好的解法思路、建議或者其餘問題,能夠下方留言交流,點贊、留言、轉發就是對我最大的回報和支持!

相關文章
相關標籤/搜索