์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 1303๋ฒˆ: ์ „์Ÿ - ์ „ํˆฌ (DFS/BFS, C++)

PROGRAMMING/Algorithm

by koharin 2021. 3. 2. 18:09

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“ ๋ฌธ์ œํ’€์ด ๊ณผ์ •


์ด๋ฒˆ ๋ฌธ์ œ๋„ BOJ:2667(๋‹จ์ง€๋ฒˆํ˜ธ๋ถ™์ด๊ธฐ) ๋ฌธ์ œ์™€ ์œ ์‚ฌํ•˜๋‹ค.

๊ฐ ๋ณ‘์‚ฌ graph[x][y]๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ƒ, ํ•˜, ์ขŒ, ์šฐ์˜ 4๊ฐ€์ง€ ๊ฒฝ์šฐ์—๋งŒ ์ธ์ ‘ํ•œ ๊ฒƒ์œผ๋กœ ๊ฐ„์ฃผํ•œ๋‹ค.

x-1 y

x y-1

x y+1

x+1 y

๋”ฐ๋ผ์„œ graph[x][y] ๊ธฐ์ค€ ์œ„์˜ 4๊ฐ€์ง€ ๊ฒฝ์šฐ์— ๋Œ€ํ•ด ํ•ด๋‹น ์ •์ ์ด ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๊ณ , graph[x][y]์™€ ๊ฐ’์ด ๊ฐ™์œผ๋ฉด ๋ฐฉ๋ฌธํ•œ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ธ์ ‘ํ•œ ๊ฒƒ์œผ๋กœ cnt๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

์ด๋•Œ ๋‹ค์Œ ๋ฐฉ๋ฌธํ•˜๋Š” graph[nx][ny]์—์„œ nx์™€ ny๋Š” ์ „์Ÿํ„ฐ M x N ํฌ๊ธฐ ๋ฒ”์œ„ ๋‚ด์— ์žˆ๋Š” ๊ฒƒ์„ ๋Œ€์ƒ์œผ๋กœ ํƒ์ƒ‰ํ•œ๋‹ค.

๋งŒ์•ฝ ์ดˆ๊ธฐ graph[x][y]์— ๋Œ€ํ•œ ํ•จ์ˆ˜ ํ˜ธ์ถœ์ด ๋๋‚˜๊ณ  main ํ•จ์ˆ˜๋กœ ๋ฆฌํ„ดํ•˜๋ฉด graph[x][y] ๊ธฐ์ค€ ๋ชจ๋“  ์ธ์ ‘ํ•œ ์ •์ ๋“ค์— ๋Œ€ํ•ด ๋ฐฉ๋ฌธํ•œ ๊ฒƒ์œผ๋กœ, cnt์— ๋Œ€ํ•œ ๊ฐ’์˜ ์ œ๊ณฑ์„ W์ด์—ˆ์œผ๋ฉด result[0]์—, B์ด์—ˆ์œผ๋ฉด result[1]์— ๋”ํ•ด๊ฐ„๋‹ค.

 

 

๐Ÿ’ป C++ ์ œ์ถœ์ฝ”๋“œ


#include <iostream>
#include <deque>
using namespace std;
int visited[100][100];
int dx[] = {-1, 0, 0, 1};
int dy[] = {0, -1, 1, 0};

void DFS(int x, int y, deque<char> *graph, int *cnt, int N, int M){
    (*cnt)++;
    visited[x][y] = 1;
    
    for(int i=0; i<4; i++){
        int nx = x + dx[i]; int ny = y + dy[i];
        if(nx < 0 || ny < 0 || nx >= M || ny >= N) continue;
        if(!visited[nx][ny] && graph[nx][ny] == graph[x][y]) DFS(nx, ny, graph, cnt, N, M);
    }
}

int main(){
    int N, M; // N: ๊ฐ€๋กœ, M: ์„ธ๋กœ
    scanf("%d %d", &N, &M);
    deque<char> graph[M];
    deque<int> result;
    result.push_back(0);
    result.push_back(0);

    for(int i=0; i<M; i++){
        string str;
        cin >> str;
        for(char c: str) graph[i].push_back(c);
    }
    
    for(int i=0; i<M; i++){
        for(int j=0; j<N; j++){
            int cnt=0;
            if(!visited[i][j]){
                DFS(i, j, graph, &cnt, N, M);
                if(graph[i][j] == 'W') result[0] += cnt*cnt;
                else result[1] += cnt*cnt;
            }
        }
    }
    printf("%d %d\n", result[0], result[1]);
}

โ—โ— ์ฃผ์˜ํ•ด์•ผ ํ•  ์ ์€, ๊ฐ€๋กœ๊ฐ€ M์ด๊ณ , ์„ธ๋กœ๊ฐ€ N์ด๋‹ค. ์ฆ‰, x์— ๋Œ€ํ•œ ๋ฒ”์œ„๊ฐ€ 0~M-1๊นŒ์ง€, y์— ๋Œ€ํ•œ ๋ฒ”์œ„๊ฐ€ 0~N-1๊นŒ์ง€์ด๋‹ค.

๊ณ„์† ์˜ค๋‹ต์„ ๋ฐ›๋Š”๋‹ค๋ฉด, ์ด ๋ถ€๋ถ„์„ ๋‹ค์‹œ ํ™•์ธํ•ด๋ณด์ž. 

 

 

๐Ÿ‘ ๊ฒฐ๊ณผ


728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ