출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]
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 함수를 간단한 형태로 유지될 수 있게 설계했다.
백준 1707 이분 그래프(dfs) (0) | 2020.07.26 |
---|---|
백준 1389 케빈 베이컨의 6단계 법칙(Floyd Warshall) (0) | 2020.07.26 |
백준 1987 알파벳(dfs) (0) | 2020.07.25 |
백준 2583 영역 구하기(dfs) (0) | 2020.07.25 |
백준 2468 안전 영역(dfs) (0) | 2020.07.23 |
댓글 영역