1 class Solution 2 { 3 int temp; 4 public: 5 vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) 6 { 7 int m = image.size(),n = image[0].size(); 8 temp = image[sr][sc];//备份起始坐标的值 9 DFS(image,m,n,sr,sc,newColor); 10 return image; 11 } 12 void DFS(vector<vector<int>>& image,int m,int n,int i,int j,int newColor) 13 { //如果当前值不为起始坐标的值 或者 当前值为newColor,则直接返回return 14 if(i < 0 || i > m - 1 || j < 0 || j > n - 1 || image[i][j] != temp || image[i][j] == newColor) return; 15 image[i][j] = newColor;//当前值置为newColor 16 //四个方向进行DFS 17 DFS(image,m,n,i,j + 1,newColor); 18 DFS(image,m,n,i,j - 1,newColor); 19 DFS(image,m,n,i + 1,j,newColor); 20 DFS(image,m,n,i - 1,j,newColor); 21 } 22 };