1. 程式人生 > 實用技巧 >【力扣】733. 影象渲染

【力扣】733. 影象渲染

有一幅以二維整數陣列表示的圖畫,每一個整數表示該圖畫的畫素值大小,數值在 0 到 65535 之間。

給你一個座標(sr, sc)表示影象渲染開始的畫素值(行 ,列)和一個新的顏色值newColor,讓你重新上色這幅影象。

為了完成上色工作,從初始座標開始,記錄初始座標的上下左右四個方向上畫素值與初始座標相同的相連畫素點,接著再記錄這四個方向上符合條件的畫素點與他們對應四個方向上畫素值與初始座標相同的相連畫素點,……,重複該過程。將所有有記錄的畫素點的顏色值改為新的顏色值。

最後返回經過上色渲染後的影象。

示例 1:

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

sr = 1, sc = 1, newColor = 2
輸出: [[2,2,2],[2,2,0],[2,0,1]]
解析:
在影象的正中間,(座標(sr,sc)=(1,1)),
在路徑上所有符合條件的畫素點的顏色都被更改成2。
注意,右下角的畫素沒有更改為2,
因為它不是在上下左右四個方向上與初始點相連的畫素點。
注意:

image 和image[0]的長度在範圍[1, 50] 內。
給出的初始點將滿足0 <= sr < image.length 和0 <= sc < image[0].length。
image[i][j] 和newColor表示的顏色值在範圍[0, 65535]內。

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/flood-fill

時間複雜度:O(n*m)

public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if(sr < 0 || sc < 0 || sr >= image.length || sc >= image[0].length || image[sr][sc] == newColor){
            return image;
        }
        int currentValue = image[sr][sc];
         
int x = image.length; int y = image[0].length; image[sr][sc] = newColor; // if((sr-1>=0) && image[sr-1][sc] == currentValue){ floodFill(image,sr-1,sc,newColor); } // if((sr+1< x) && image[sr+1][sc] == currentValue){ floodFill(image,sr+1,sc,newColor); } // if(sc-1 >= 0 && image[sr][sc-1] == currentValue ){ floodFill(image,sr,sc-1,newColor); } // if(sc+1 < y && image[sr][sc+1] == currentValue ){ floodFill(image,sr,sc+1,newColor); } return image; }