알고리즘과 자료구조/백준

BOJ 1012 유기농 배추

bggbr 2019. 12. 24. 12:45
#include <iostream>
#include <cstring>
using namespace std;
#define endl "\n"
#define MAX 51
const int dy[4] = {-1, 1, 0, 0};
const int dx[4] = {0, 0, -1, 1};
int tc;
int m, n, k;
int totalLand;
int map[MAX][MAX];
bool check[MAX][MAX];
void dfs(int y, int x){
    for(int i = 0; i < 4; i++){
        int ny = dy[i] + y;
        int nx = dx[i] + x;
        if(ny >= 0 && ny < n && nx >= 0 && nx < m){
            if(map[ny][nx] && !check[ny][nx]){
                check[ny][nx] = true;
                dfs(ny, nx);
            }

        }
    }
}
int main(void){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    cin >> tc;
    while(tc--){
        memset(map, 0, sizeof(map));
        memset(check, 0, sizeof(check));
        totalLand = 0;
        cin >> m >> n >> k;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                map[i][j] = 0;
            }
        }
        while(k--){
            int x, y;
            cin >> x >> y;
            map[y][x] = 1;
        }
        for(int i = 0; i < n; i++){
            for(int j = 0; j < m; j++){
                if(map[i][j] && !check[i][j]){
                    dfs(i, j);
                    totalLand++;
                }
            }
        }
        cout << totalLand << endl;
    }
}

'알고리즘과 자료구조 > 백준' 카테고리의 다른 글

BOJ 14501 퇴사  (0) 2019.12.30
BOJ 1389 케빈 베이컨의 6단계 법칙  (0) 2019.12.27
BOJ 2573 빙산  (0) 2019.12.24
BOJ 15649 N과 M (1), 순열  (0) 2019.11.21
BOJ 15650 N과 M (2), 조합  (0) 2019.11.21