ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 유기농 배추
    백준알고리즘 2019. 7. 17. 02:25
    #include<queue>
    #include<cstdio>
    #include<utility>
    #include<vector>
    #include<iostream>
    
    using namespace std;
    
    int tc;
    int a[51][51];
    bool d[51][51];
    int m,n, k;
    
    int dx[] = {0,0,1,-1};
    int dy[] = {1,-1,0,0};
    void bfs(int x, int y){
        queue<pair<int, int>> q;
        q.push(make_pair(x,y));
        d[x][y] = true;
        while(!q.empty()){
            x = q.front().first; y = q.front().second;
            q.pop();
            for(int i = 0; i < 4; i++){
                int nx = x+dx[i]; int ny = y+dy[i];
                if(nx >= 0 && nx < n && ny >=0 &&ny < m){
                    if(d[nx][ny] == false){
                        if(a[nx][ny] == 1){
                            d[nx][ny] = true;
                            q.push(make_pair(nx,ny));
                        }
                    }
                }
            }
        }
    }
    void initial(){
        for(int i = 0; i < 51; i++){
            for(int j = 0; j < 51; j++){
                a[i][j] = 0;
                d[i][j] =false;
            }
        }
    }
    
    int main(){
        scanf("%d", &tc);
        for(int t = 1; t <= tc; t++){
            cin>>m>>n>>k;
            for(int i = 0; i < k; i++){
                int x, y;
                scanf("%d %d", &x, &y);
                a[y][x] = 1;
            }
            int result = 0;
            for(int i = 0; i< n; i++){
                for(int j = 0; j< m; j++){
                    if(d[i][j] == false){
                        if(a[i][j] == 1){
                            result+=1;
                            bfs(i,j);
                        }
                    }
                }
            }
    
            printf("%d\n", result);
            initial();
        }
        return 0;
    }

    BFS문제, 아직도 짜증나는것중에 하나는, 입력순서가 꼭 배열의 [][] 순서와 같지않다는점 정도

    난이도 하

    '백준알고리즘' 카테고리의 다른 글

    보물섬  (0) 2019.07.17
    시험 감독  (0) 2019.07.17
    연구소  (0) 2019.07.17
    기지국  (0) 2019.07.14
    욕심쟁이 판다  (0) 2019.07.13

    댓글

Designed by Tistory.