Leetcode 733. 影象渲染(牛,做出來了)
阿新 • • 發佈:2022-05-28
有一幅以 m x n 的二維整數陣列表示的圖畫 image ,其中 image[i][j] 表示該圖畫的畫素值大小。
你也被給予三個整數 sr , sc 和 newColor 。你應該從畫素 image[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,因為它不是在上下左右四個方向上與初始點相連的畫素點。
示例 2:
輸入: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
輸出: [[2,2,2],[2,2,2]]
提示:
- m == image.length
- n == image[i].length
- 1 <= m, n <= 50
- 0 <= image[i][j], newColor < 216
- 0 <= sr < m
- 0 <= sc < n
主要思路:
利用遞迴解決+map
這邊出現個小問題:自定義結構體作為map時,不知道怎麼處理唯一性,我這邊出現鍵值相同的(有待處理)
Code:
class Solution { public: typedef struct pos { int x; int y; bool operator < (const pos &o) const { if((x==o.x)&&(y==o.y)) return false; return true; } }pos; map<pos,int>posMap; pair<map<pos,int>::iterator, bool> ret; void fss(vector<vector<int>>& image,int x,int y,int num) { if(x<0) return; if(x>=image.size()) return; if(y<0) return; if(y>=image[0].size()) return; if(image[x][y]==num) { // cout<<"x="<<x<<" y="<<y<<endl; pos p; p.x=x; p.y=y; ret= posMap.insert(pair<pos,int>(p,1)); if(!ret.second) { return; } fss(image,x-1,y,num);//左遞迴 fss(image,x+1,y,num);//右遞迴 fss(image,x,y-1,num);//上遞迴 fss(image,x,y+1,num);//左遞迴 } } vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int num=image[sr][sc]; vector<vector<int>> res; fss(image,sr,sc,num); map<pos,int>::iterator it; for(it=posMap.begin();it!=posMap.end();++it) { // cout<<it->first.x<<"++"<<it->first.y<<endl; image[it->first.x][it->first.y]=newColor; } return image; } };