Advertisement
tepyotin2

Floodfill

May 1st, 2025
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. // Directions: up, down, top-left, bottom-right
  8. int dx[] = {-1, 1, -1, 1};
  9. int dy[] = {0, 0, -1, 1};
  10.  
  11. int main() {
  12.     int n, x, y;
  13.     cin >> n >> x >> y;
  14.  
  15.     vector<vector<int>> maze(n, vector<int>(n));
  16.     vector<vector<bool>> visited(n, vector<bool>(n, false));
  17.  
  18.     // Read the maze
  19.     for (int i = 0; i < n; ++i)
  20.         for (int j = 0; j < n; ++j)
  21.             cin >> maze[i][j];
  22.  
  23.     // Check if starting point is blocked
  24.     if (maze[x][y] == 1) {
  25.         cout << 0 << endl;
  26.         return 0;
  27.     }
  28.  
  29.     int count = 0;
  30.     queue<pair<int, int>> q;
  31.     q.push({x, y});
  32.     visited[x][y] = true;
  33.  
  34.     while (!q.empty()) {
  35.         auto [cx, cy] = q.front(); q.pop();
  36.         count++;
  37.  
  38.         for (int i = 0; i < 4; ++i) {
  39.             int nx = cx + dx[i];
  40.             int ny = cy + dy[i];
  41.  
  42.             if (nx >= 0 && nx < n && ny >= 0 && ny < n &&
  43.                 !visited[nx][ny] && maze[nx][ny] == 0) {
  44.                 visited[nx][ny] = true;
  45.                 q.push({nx, ny});
  46.             }
  47.         }
  48.     }
  49.  
  50.     cout << count << endl;
  51.     return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement