알고리즘 풀이/백준(Boj)

백준(BOJ) 10026번 적록색약

100win10 2019. 7. 16. 00:57

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



적록색약이 아닌 사람이 봤을 때 구역의 수는 총 4개이다. (빨강 2, 파랑 1, 초록 1) 하지만, 적록색약인 사람은 구역을 3개 볼 수 있다. (빨강-초록 2, 파랑 1)

그림이 입력으로 주어졌을 때, 적록색약인 사람이 봤을 때와 아닌 사람이 봤을 때 구역의 수를 구하는 프로그램을 작성하시오.





나의풀이 : 


색약이 아닐 경우 R,G,B 한번씩 DFS를 통하여 답을 구하고 색약일 경우 구역에 G들을 R로 바꾼후 R,B 한번씩 DFS를 통하여 답을 구하여 출력하였다.




코드 ( C ++ )


#include <iostream>

#include <algorithm>

#include <cstring>

using namespace std;

int N;

const int MAX = 101;

char section[MAX][MAX];

bool check[MAX][MAX];

const int dy[4] = { 1, -1, 0, -0 };

const int dx[4] = { 0, 0, -1, 1 };


void DFS(int y, int x, char alphabet) { 

check[y][x] = true;

for (int i = 0; i < 4; ++i)

{

int ny = y + dy[i];

int nx = x + dx[i];


if (ny >= 0 && ny < N && nx >= 0 && ny < N)

if (check[ny][nx] == false && section[ny][nx] == alphabet)

DFS(ny, nx, alphabet);

}

}

void Init()  // 색약을 위해  G를 R로 바꾼다.

{

for(int i=0; i<=N; ++i)

for (int j = 0; j <= N; ++j)

{

if (section[i][j] == 'G')

section[i][j] = 'R';

}

// check 도 다시 false로 초기화 해주자.

for (int i = 0; i <= N; ++i)

for (int j = 0; j <= N; ++j)

check[i][j] = false;

}

int main()

{

cin >> N;

for(int i=0; i<N; ++i)

for (int j = 0; j < N; ++j)

{

cin >> section[i][j];

}

char RGB[3] = { 'R', 'G', 'B' };

int sum = 0;

for (int a = 0; a < 3; ++a) {

char rgb = RGB[a];

int cnt = 0;

for (int i = 0; i < N; ++i) {

for (int j = 0; j < N; ++j) {

if (check[i][j] == false && section[i][j] == rgb) {

DFS(i, j, rgb);

cnt++;

}

}

}

sum += cnt;

}


//색약을 위한 초기화 section의 G를 R로 바꿔주었다.

Init();

char RB[2] = { 'R','B' }; // R,B일때만 구해보자.

int sum2 = 0;

for (int a = 0; a < 2; ++a) {

char rgb = RB[a];

int cnt = 0;

for (int i = 0; i < N; ++i) {

for (int j = 0; j < N; ++j) {

if (check[i][j] == false && section[i][j] == rgb) {

DFS(i, j, rgb);

cnt++;

}

}

}

sum2 += cnt;

}

cout << sum << " " << sum2 << endl;

return 0;

}