ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • BFS 기본 형식 - 2차원 배열(Flood Fill)
    BFS 2023. 12. 3. 14:39

    Flood Fill 알고리즘은 주어진 시작점으로 부터 연결된 영역을 찾는 알고리즘이다. 

    #include <bits/stdc++.h>
    using namespace std;
    #define X first
    #define Y second // pair에서 first, second를 줄여서 쓰기 위해서 사용
    int board[502][502]; // 1이 파란 칸, 0이 빨간 칸에 대응
    bool vis[502][502]; // 해당 칸을 방문했는지 여부를 저장
    int n, m;
    int dx[4] = {1, 0, -1, 0};
    int dy[4] = {0, 1, 0, -1}; // 상하좌우 네 방향을 의미
    
    int main() {
        ios::sync_with_stdio(0);
        cin.tie(0);
        cin >> n >> m;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < m; j++)
                cin >> board[i][j];
        queue<pair<int, int>> Q;
        vis[0][0] = 1; // (0, 0)에서부터 BFS를 시작하기 위한 준비
        Q.push({0, 0});
        while(!Q.empty()){
            auto cur = Q.front(); Q.pop();
            for(int dir = 0; dir < 4; i++){ // 상하좌우 칸을 살펴볼 것이다.
                int nx = cur.X + dx[dir];
                int ny = cur.Y + dy[dir]; // nx, ny에 dir에서 정한 방향의 인접한 칸의 좌표가 들어감
                if(nx < 0 || nx >= n || ny < 0 || ny >= m) continue; // 범위 밖일 경우 넘어감
                if(board[nx][ny] != 1 || vis[i][j] == 1) continue; // 이미 방문한 칸이거나 파란 칸이 아닐 경우
                vis[nx][ny] = 1;
                Q.push({nx, ny}); // (nx, ny)를 방문했다고 명시
            }
        }
        // (0, 0)을 시작점으로 하는 BFS가 종료됨.
        
        return 0;
    }

    'BFS' 카테고리의 다른 글

    BFS 기본형식 - 최단거리 계산  (1) 2023.12.03
Designed by Tistory.