1. 程式人生 > >LeetCode733 影象渲染

LeetCode733 影象渲染

 

有一幅以二維整數陣列表示的圖畫,每一個整數表示該圖畫的畫素值大小,數值在 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]內。

 


 

 

/*
演算法思想:
    這道題給了我們一個用二維陣列表示的影象,不同的數字代表不同的顏色,給了我們一個起始點座標,還有一個新的顏色,讓我們把起始點的顏色以及其相鄰的同樣的顏色都換成新的顏色。那麼實際上就是一個找相同區間的題,我們可以用BFS或者DFS來做。先來看BFS的解法,我們使用一個佇列queue來輔助,首先將給定點放入佇列中,然後進行while迴圈,條件是queue不為空,然後進行類似層序遍歷的方法,取出隊首元素,將其賦值為新的顏色,然後遍歷周圍四個點,如果不越界,且周圍的顏色跟起始顏色相同的話,將位置加入佇列中。
*/ //演算法實現: /* class Solution { public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int m = image.size(), n = image[0].size(), color = image[sr][sc]; vector<vector<int>> res = image; vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}}; queue<pair<int, int>> q{{{sr, sc}}}; while (!q.empty()) { int len = q.size(); for (int i = 0; i < len; ++i) { auto t = q.front(); q.pop(); res[t.first][t.second] = newColor; for (auto dir : dirs) { int x = t.first + dir[0], y = t.second + dir[1]; if (x < 0 || x >= m || y < 0 || y >= n || res[x][y] != color) continue; q.push({x, y}); } } } return res; } };
*/ /* 演算法思想: DFS的寫法相對簡潔一些,首先判斷如果給定位置的顏色跟新的顏色相同的話,直接返回,否則就對給定位置呼叫遞迴函式。在遞迴函式中,如果越界或者當前顏色跟起始顏色不同,直接返回。否則就給當前位置賦上新的顏色,然後對周圍四個點繼續呼叫遞迴函式。 */ //演算法實現: class Solution { public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { if (image[sr][sc] == newColor) return image; helper(image, sr, sc, image[sr][sc], newColor); return image; } void helper(vector<vector<int>>& image, int i, int j, int color, int newColor) { int m = image.size(), n = image[0].size(); if (i < 0 || i >= m || j < 0 || j >= n || image[i][j] != color) return; image[i][j] = newColor; helper(image, i + 1, j, color, newColor); helper(image, i, j + 1, color, newColor); helper(image, i - 1, j, color, newColor); helper(image, i, j - 1, color, newColor); } };