0733.cpp (1007B)
1 class Solution { 2 int m, n, src, color; 3 vector<vector<int>> *image; 4 queue<pair<int, int>> q; 5 6 int valid(int sr, int sc) { return sr >= 0 && sr < m && sc >= 0 && sc < n; } 7 8 void add(int sr, int sc) { 9 if (valid(sr, sc) && (*image)[sr][sc] == src) { 10 (*image)[sr][sc] = color; 11 q.push(make_pair(sr, sc)); 12 } 13 } 14 15 public: 16 vector<vector<int>> floodFill(vector<vector<int>> &image, int sr, int sc, int color) { 17 src = image[sr][sc]; 18 if (src == color) return image; 19 20 m = image.size(); 21 n = image[0].size(); 22 this->color = color; 23 this->image = ℑ 24 25 q.push(make_pair(sr, sc)); 26 image[sr][sc] = color; 27 28 while (!q.empty()) { 29 int sr = q.front().first; 30 int sc = q.front().second; 31 q.pop(); 32 33 add(sr + 1, sc); 34 add(sr - 1, sc); 35 add(sr, sc + 1); 36 add(sr, sc - 1); 37 } 38 39 return image; 40 } 41 };