적록색약 10026

PublicMinsu·2023년 1월 1일
0

문제

접근 방법

같은 색상을 탐색하고 탐색하는 과정에서 빨강, 초록을 같은 색상으로 일치시키면 다음 탐색에서는 같은 것으로 인식된다고 생각하였다.

코드

#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int N, cnt = 0;
    cin >> N;
    vector<vector<char>> map(N, vector<char>(N));
    vector<vector<bool>> visted(N, vector<bool>(N));
    queue<pair<int, int>> bfs;
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
        {
            char k;
            cin >> k;
            map[i][j] = k;
        }
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
        {
            if (visted[i][j])
                continue;
            char color = map[i][j];
            ++cnt;
            if (map[i][j] == 'G')
            {
                map[i][j] = 'R';
            }
            bfs.push({i, j});
            while (!bfs.empty())
            {
                auto cur = bfs.front();
                bfs.pop();
                for (int k = 0; k < 4; ++k)
                {
                    pair<int, int> next = {cur.first + dy[k], cur.second + dx[k]};
                    if (next.first < 0 || next.second < 0 || next.first >= N || next.second >= N)
                        continue;
                    if (visted[next.first][next.second] || color != map[next.first][next.second])
                        continue;
                    if (map[next.first][next.second] == 'G')
                    {
                        map[next.first][next.second] = 'R';
                    }
                    visted[next.first][next.second] = true;
                    bfs.push(next);
                }
            }
        }
    cout << cnt << " ";
    cnt = 0;
    fill(visted.begin(), visted.end(), vector<bool>(N));
    for (int i = 0; i < N; ++i)
        for (int j = 0; j < N; ++j)
        {
            if (visted[i][j])
                continue;
            char color = map[i][j];
            ++cnt;
            bfs.push({i, j});
            while (!bfs.empty())
            {
                auto cur = bfs.front();
                bfs.pop();
                for (int k = 0; k < 4; ++k)
                {
                    pair<int, int> next = {cur.first + dy[k], cur.second + dx[k]};
                    if (next.first < 0 || next.second < 0 || next.first >= N || next.second >= N)
                        continue;
                    if (visted[next.first][next.second] || color != map[next.first][next.second])
                        continue;
                    visted[next.first][next.second] = true;
                    bfs.push(next);
                }
            }
        }
    cout << cnt;
    return 0;
}

풀이

전체적으로 2번의 탐색이 필요하다.
첫 탐색 때 빨강, 초록 중 하나로 통일해주면 다음 탐색할 때는 2가지 색만이 존재하게 된다.
즉 첫 탐색 때는 수정+탐색을 거치고 두 번째 탐색은 탐색만을 해주면 된다.

profile
연락 : publicminsu@naver.com

0개의 댓글