1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| vector<vector<int> > floodFill(vector<vector<int> >& image, int sr, int sc, int newColor) { if(image.empty() || image[0].empty()) return image; int old = image[sr][sc]; if(old == newColor) { return image; } int next[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; queue<pair<int, int> > q; q.push(pair<int, int>(sr, sc)); while(q.size()) { pair<int, int> t = q.front(); q.pop(); image[t.first][t.second] = newColor; for(int i = 0; i < 4; i++) { int nx = t.first + next[i][0], ny = t.second + next[i][1]; if(nx >= 0 && nx < image.size() && ny >= 0 && ny < image[0].size() && image[nx][ny] == old) { q.push(pair<int, int>(nx, ny)); } } } return image; }
|