1 minute read

코드

#include <bits/stdc++.h>
#define ll long long
using namespace std;
#define X first
#define Y second


int dx[4] = { 1,0,-1,0 };
int dy[4] = { 0,1,0,-1 };
string lev[100];
int n;
void bfs(bool arr[][101], queue<pair<int, int>>& q, char ch)
{
    while (!q.empty())
    {
        auto cur = q.front(); q.pop();
        for (int dir = 0; dir < 4; dir++)
        {
            int nx = cur.X + dx[dir];
            int ny = cur.Y + dy[dir];
            if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
            if (arr[nx][ny] != 0 || lev[nx][ny] != ch) continue;
            arr[nx][ny] = 1;
            q.push({ nx,ny });
        }
    }
    return;
}

int main(void) 
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cin >> n;
    bool normal[101][101] = {0,};
    bool abnormal[101][101] = {0,};
    for (int i = 0; i < n; i++)
        cin >> lev[i];
    queue<pair<int, int>> nor,ab;
    int abns = 0, norans = 0;
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if ((lev[i][j] == 'R' || lev[i][j] == 'G') && abnormal[i][j] == 0)
            {
                ab.push({ i,j });
                abns++;
                while (!ab.empty())
                {
                    auto cur = ab.front(); ab.pop();
                    for (int dir = 0; dir < 4; dir++)
                    {
                        int nx = cur.X + dx[dir];
                        int ny = cur.Y + dy[dir];
                        if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue;
                        if (abnormal[nx][ny] != 0 || lev[nx][ny] == 'B') continue;
                        abnormal[nx][ny] = 1;
                        ab.push({ nx,ny });
                    }
                }
            }
            if (lev[i][j] == 'B' && abnormal[i][j] == 0)
            {
                ab.push({ i,j });
                abns++;
                bfs(abnormal, ab, 'B');
            }
            if (lev[i][j] == 'R' && normal[i][j] == 0)
            {
                nor.push({ i,j });
                norans++;
                bfs(normal, nor, 'R');
            }
            if (lev[i][j] == 'G' && normal[i][j] == 0)
            {
                nor.push({ i,j });
                norans++;
                bfs(normal, nor, 'G');
            }
            if (lev[i][j] == 'B' && normal[i][j] == 0)
            {
                nor.push({ i,j });
                norans++;
                bfs(normal, nor, 'B');
            }
               
        }
    }
    cout << norans << " " << abns;
    return 0;
}

코드를 막짜서 가독성이 좋지 않다.
체크배열도 하나로해도 통과할 수 있고 함수에서 char없이도 통과할 수 있다. 코드를 못생기게 짯다. 최적화 하면 체크배열도 하나로 퉁칠 수 있다.

Leave a comment