classSolution { public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { vector<vector<int>> new_image(image); int oldColor = image[sr][sc]; // 例子:oldColor = 1 if(oldColor != newColor){ // 新的颜色不同于旧颜色才更新 DFS(new_image,sr,sc,oldColor,newColor); // 深度优先搜索 } return new_image; } private: voidDFS(vector<vector<int>> &new_image, int r,int c,int old_color,int new_color){ int row_num = new_image.size(), col_num = new_image[0].size(); //越界,或者颜色不相等返回,例子:old_color = 1,只更新位置color = 1的地方 if(r < 0 || r >= row_num || c < 0 || c >= col_num || new_image[r][c] != old_color){ return; } new_image[r][c] = new_color; DFS(new_image,r-1,c,old_color,new_color); DFS(new_image,r+1,c,old_color,new_color); DFS(new_image,r,c-1,old_color,new_color); DFS(new_image,r,c+1,old_color,new_color); } };
看到一个解法,作者:OrangeMan,简洁易懂,优秀。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) { int oldColor = image[sr][sc]; //记录旧坐标的像素 if (image[sr][sc] == newColor) return image; //颜色相同则无需修改 image[sr][sc] = newColor; //染色 int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; //上右下左 for (int i = 0; i < 4; i ++) { int x = sr + dx[i], y = sc + dy[i]; if (x >=0 && y >= 0 && x < image.size() && y < image[0].size() && image[x][y] == oldColor) floodFill (image, x, y, newColor); } return image; } };
vector<int> dx = {-1,1,0,0}; vector<int> dy = {0,0,-1,1};
for(int i = 0; i < numr; ++i){ for(int j = 0; j < numc; ++j){ if(matrix[i][j] == 0){ // 如果是 0 结果里面直接就为 0 res[i][j] = 0; q.push(make_pair(i, j)); // 并且将 0 推入队列中 } } } while(!q.empty()){ // BFS int x = q.front().first; // 获取 x,y 坐标 int y = q.front().second; q.pop(); // 推出 for(int j = 0;j<4;++j){ // 遍历 int nx = x + dx[j]; int ny = y + dy[j]; if(nx >= 0 && nx<numr && ny >= 0 && ny < numc && res[nx][ny]>res[x][y]+1){ res[nx][ny] = res[x][y] + 1; // 默认值为INT_MAX,对比,选择最短路径 q.push(make_pair(nx, ny)); // 然后推入附近的坐标 } } } return res; // 返回结果 } };
题目:钥匙和房间
有 N 个房间,开始时你位于 0 号房间。每个房间有不同的号码:0,1,2,…,N-1,并且房间里可能有一些钥匙能使你进入下一个房间。 在形式上,对于每个房间 i 都有一个钥匙列表 rooms[i],每个钥匙 rooms[i][j]由[0,1,…,N-1]中的一个整数表示,其中 N=rooms.length。钥匙 rooms[i][j]=v 可以打开编号为 v 的房间。