Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
- vector<vector<int>> result = image;
- int n = image.size();
- int m = image[0].size();
- vector<vector<bool>> visited(n, vector<bool>(m, false));
- queue<int> q;
- q.push(sr);
- q.push(sc);
- visited[sr][sc] = true;
- int s_color = image[sr][sc];
- result[sr][sc] = color;
- while(!q.empty()) {
- int ci = q.front();
- q.pop();
- int cj = q.front();
- q.pop();
- if(ci + 1 < n and !visited[ci + 1][cj] and image[ci + 1][cj] == s_color) {
- q.push(ci + 1);
- q.push(cj);
- visited[ci + 1][cj] = true;
- result[ci + 1][cj] = color;
- }
- if(ci - 1 >= 0 and !visited[ci - 1][cj] and image[ci - 1][cj] == s_color) {
- q.push(ci - 1);
- q.push(cj);
- visited[ci - 1][cj] = true;
- result[ci - 1][cj] = color;
- }
- if(cj + 1 < m and !visited[ci][cj + 1] and image[ci][cj + 1] == s_color) {
- q.push(ci);
- q.push(cj + 1);
- visited[ci][cj + 1] = true;
- result[ci][cj + 1] = color;
- }
- if(cj - 1 >= 0 and !visited[ci][cj - 1] and image[ci][cj - 1] == s_color) {
- q.push(ci);
- q.push(cj - 1);
- visited[ci][cj - 1] = true;
- result[ci][cj - 1] = color;
- }
- }
- return result;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement