๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 10026๋ฒˆ - ์ ๋ก์ƒ‰์•ฝ

by dkswnkk 2021. 10. 16.
 

10026๋ฒˆ: ์ ๋ก์ƒ‰์•ฝ

์ ๋ก์ƒ‰์•ฝ์€ ๋นจ๊ฐ„์ƒ‰๊ณผ ์ดˆ๋ก์ƒ‰์˜ ์ฐจ์ด๋ฅผ ๊ฑฐ์˜ ๋Š๋ผ์ง€ ๋ชปํ•œ๋‹ค. ๋”ฐ๋ผ์„œ, ์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ์ด ๋ณด๋Š” ๊ทธ๋ฆผ์€ ์•„๋‹Œ ์‚ฌ๋žŒ์ด ๋ณด๋Š” ๊ทธ๋ฆผ๊ณผ๋Š” ์ข€ ๋‹ค๋ฅผ ์ˆ˜ ์žˆ๋‹ค. ํฌ๊ธฐ๊ฐ€ N×N์ธ ๊ทธ๋ฆฌ๋“œ์˜ ๊ฐ ์นธ์— R(๋นจ๊ฐ•), G(์ดˆ๋ก)

www.acmicpc.net

 

//  Copyright © 2021 ์•ˆ์ฃผํ˜•. All rights reserved.
// 
//  https://www.acmicpc.net/problem/10026
//  BOJ10026 ์ ๋ก์ƒ‰์•ฝ
#include <iostream>
#include <queue>
#include <memory.h>

using namespace std;

int N,ans1,ans2;    //NxN, ans1=์ ๋ก์ƒ‰์•ฝ ์•„๋‹Œ์‚ฌ๋žŒ์ด ๋ดค์„๋•Œ, ans=์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ์ด ๋ดค์„๋•Œ
char map[101][101];
int visited[101][101];
queue<pair<int, int>>q;
int dx[] = { 0,0,-1,1 };    //์ƒ ํ•˜ ์ขŒ ์šฐ
int dy[] = { -1,1,0,0 };

void reset() {
    memset(visited,0,sizeof(visited));
}
void bfs(int a, int b) {
    q.push({ a,b });
    visited[a][b] = 1;
    while (!q.empty()) {
        int x = q.front().first;
        int 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 < N) {    //๊ตฌ์—ญ์˜ ๋ฒ”์œ„๋ฅผ ๋„˜์–ด์„œ์ง€ ์•Š์„๋•Œ
                if (!visited[nx][ny] && (map[nx][ny] == map[x][y])) {
                    visited[nx][ny] = 1;
                    q.push({ nx,ny });

                }
            }
        }
    }
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    cin >> N;
    for (int i = 0; i < N; i++) {    //๊ทธ๋ฆผ ์ •๋ณด ์ž…๋ ฅ.
        for (int k = 0; k < N; k++) {
            cin >> map[i][k];
        }
    }


    for (int i = 0; i < N; i++) {    //์ ๋ก์ƒ‰์•ฝ ์•„๋‹Œ์‚ฌ๋žŒ์ด ๋ณผ๋•Œ ํƒ์ƒ‰
        for (int k = 0; k < N; k++) {
            if (!visited[i][k]) {
                bfs(i, k);
                ans1++;
            }
        }
    }
    reset(); //๋ฐฉ๋ฌธ ๊ธฐ๋ก ์ดˆ๊ธฐํ™”

    for (int i = 0; i < N; i++) {    //์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ์ด ๋ณผ๋•Œ๋ฅผ ํƒ์ƒ‰ํ•˜๊ธฐ์œ„ํ•ด
        for (int k = 0; k < N; k++) {
            if (map[i][k] == 'G') map[i][k] = 'R';    //์ดˆ๋ก์„ ๋นจ๊ฐ•์œผ๋กœ ๋ณ€๊ฒฝ

        }
    }
    for (int i = 0; i < N; i++) {    //์ ๋ก์ƒ‰์•ฝ์ธ ์‚ฌ๋žŒ์ด ๋ณผ๋•Œ ํƒ์ƒ‰
        for (int k = 0; k < N; k++) {
            if (!visited[i][k]) {
                bfs(i, k);
                ans2++;
            }
        }
    }

    cout << ans1<<' '<<ans2;
}

๋Œ“๊ธ€