출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

상세 컨텐츠

본문 제목

백준 10026 적록색약(dfs)

알고리즘

by 장동균 2020. 7. 26. 00:25

본문

https://www.acmicpc.net/problem/10026

 

10026번: 적록색약

문제 적록색약은 빨간색과 초록색의 차이를 거의 느끼지 못한다. 따라서, 적록색약인 사람이 보는 그림은 아닌 사람이 보는 그림과는 좀 다를 수 있다. 크기가 N×N인 그리드의 각 칸에 R(빨강), G(

www.acmicpc.net

#include <iostream>

using namespace std;
const int MAX = 100;
int N;
string graph[MAX];
bool visited[MAX][MAX];
int cnt;
typedef struct
{
    int x, y;
} Dir;
Dir Dirmove[4] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};

void dfs(int x, int y)
{

    visited[x][y] = true;
    for (int i = 0; i < 4; i++)
    {
        int nextX = x + Dirmove[i].x;
        int nextY = y + Dirmove[i].y;
        if (0 <= nextX && nextX < N && 0 <= nextY && nextY < N && graph[x][y] == graph[nextX][nextY] && !visited[nextX][nextY])
            dfs(nextX, nextY);
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cin >> N;
    for (int i = 0; i < N; i++)
        cin >> graph[i];
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (!visited[i][j])
            {
                cnt++;
                dfs(i, j);
            }
        }
    }
    cout << cnt;
    cnt = 0;
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            visited[i][j] = false;
            if (graph[i][j] == 'G')
                graph[i][j] = 'R';
        }
    }

    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (!visited[i][j])
            {
                cnt++;
                dfs(i, j);
            }
        }
    }
    cout << " " << cnt;
}

 

이 문제 또한 전형적인 dfs 모양으로 풀었다.

visited를 초기화 시킬 때 graph 배열 자체를 수정해서 dfs 함수를 간단한 형태로 유지될 수 있게 설계했다.

관련글 더보기

댓글 영역