1. 程式人生 > >佇列&棧//影象渲染

佇列&棧//影象渲染

有一幅以二維整數陣列表示的圖畫,每一個整數表示該圖畫的畫素值大小,數值在 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]內。
class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if(image == null||sr >= image.length||sc >= image[0].length)
            return image;
        if(newColor == image[sr][sc])
            return image;
        change(image,sr,sc,image[sr][sc],newColor);
        return image;
    }
    private void change(int[][]image, int row, int col, int oldColor, int newColor){
        if(image == null||row >= image.length||col >= image[0].length||row < 0||col < 0||image[row][col] != oldColor){
            return ;
        }
        image[row][col] = newColor;
        change(image,row-1,col,oldColor,newColor);
        change(image,row,col-1,oldColor,newColor);
        change(image,row+1,col,oldColor,newColor);
        change(image,row,col+1,oldColor,newColor);
    }
}
class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        int oldColor = image[sr][sc];
        if(oldColor != newColor)
            dfs(image,sr,sc,oldColor,newColor);
        return image;
    }
    void dfs(vector<vector<int>>& image, int i, int j, int oldColor, int newColor){
        int m = image.size();
        int n = image[0].size();
        if(i < 0 || i >= m || j < 0 || j >= n || image[i][j] != oldColor) return ;
        image[i][j] = newColor;
        dfs(image,i-1,j,oldColor,newColor);
        dfs(image,i,j-1,oldColor,newColor);
        dfs(image,i+1,j,oldColor,newColor);
        dfs(image,i,j+1,oldColor,newColor);
    }
};