Advertisement
Josif_tepe

Untitled

Sep 25th, 2023
531
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. class Solution {
  2. public:
  3.     vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
  4.        
  5.         vector<vector<int>> result = image;
  6.         int n = image.size();
  7.         int m = image[0].size();
  8.         vector<vector<bool>> visited(n, vector<bool>(m, false));
  9.        
  10.         queue<int> q;
  11.         q.push(sr);
  12.         q.push(sc);
  13.         visited[sr][sc] = true;
  14.         int s_color = image[sr][sc];
  15.         result[sr][sc] = color;
  16.         while(!q.empty()) {
  17.             int ci = q.front();
  18.             q.pop();
  19.             int cj = q.front();
  20.             q.pop();
  21.            
  22.             if(ci + 1 < n and !visited[ci + 1][cj] and image[ci + 1][cj] == s_color) {
  23.                 q.push(ci + 1);
  24.                 q.push(cj);
  25.                 visited[ci + 1][cj] = true;
  26.                 result[ci + 1][cj] = color;
  27.             }
  28.             if(ci - 1 >= 0 and !visited[ci - 1][cj] and image[ci - 1][cj] == s_color) {
  29.                 q.push(ci - 1);
  30.                 q.push(cj);
  31.                 visited[ci - 1][cj] = true;
  32.                 result[ci - 1][cj] = color;
  33.             }
  34.             if(cj + 1 < m and !visited[ci][cj + 1] and image[ci][cj + 1] == s_color) {
  35.                 q.push(ci);
  36.                 q.push(cj + 1);
  37.                 visited[ci][cj + 1] = true;
  38.                 result[ci][cj + 1] = color;
  39.             }
  40.             if(cj - 1 >= 0 and !visited[ci][cj - 1] and image[ci][cj - 1] == s_color) {
  41.                 q.push(ci);
  42.                 q.push(cj - 1);
  43.                 visited[ci][cj - 1] = true;
  44.                 result[ci][cj - 1] = color;
  45.             }
  46.            
  47.         }
  48.        
  49.         return result;
  50.     }
  51. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement