题目
733. 图像渲染
我的思路
很明显的深搜或者广搜,用一个辅助矩阵来记录已经搜索过的像素点
我使用广搜来解决:
初始化队列,加入一个原始坐标
当队列不为空时,循环:取出队头,若满足条件(改色,把四周为搜索过的节点加入队列)
我的实现
class Solution { public: vector<pair<int,int>> steps ; vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { steps.push_back(make_pair<int,int>(1,0)); steps.push_back(make_pair<int,int>(-1,0)); steps.push_back(make_pair<int,int>(0,1)); steps.push_back(make_pair<int,int>(0,-1)); vector<vector<bool>> visitedMap; for(int i=0;i<image.size();i++){ visitedMap.push_back(vector<bool>(image[0].size(),false));} int rawColor = image[sr][sc]; queue<pair<int,int>> Q; visitedMap[sr][sc]=true; Q.push(make_pair(sr,sc)); while(!Q.empty()){ int x = Q.front().first; int y = Q.front().second; //cout<<x<<" "<<y<<endl; //int tempColor = image[Q.front().first][Q.front().second]; Q.pop(); if(image[x][y]==rawColor) { image[x][y] = newColor; for(auto it:steps){ if((x+it.first)>=0&&(x+it.first)<image.size()&&(y+it.second)>=0&&(y+it.second)<image[0].size()) if(visitedMap[x+it.first][y+it.second]==false){ Q.push(make_pair(x+it.first,y+it.second)); visitedMap[x+it.first][y+it.second] = true; } } } } return image; } };