Home (Python)(백준_10026)(DFS) 적록색약
Post
Cancel

(Python)(백준_10026)(DFS) 적록색약

10026번: 적록색약

DFS 풀이

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 적록색약인 경우 G를 R로 치환

from typing import List
import sys

sys.setrecursionlimit(10**5)
input=sys.stdin.readline

N = int(input())
graph = [list(input().rstrip()) for _ in range(N)]
visited = [[False] * N for _ in range(N)]

d = [(0,1), (0, -1), (1,0), (-1,0)]

def dfs(x, y):
    visited[x][y] = True
    color = graph[x][y]
    for dx, dy in d:
        nx, ny = x + dx, y + dy

        if 0 <= nx < N and 0 <= ny < N and not visited[nx][ny] and graph[nx][ny] == color:
            dfs(nx, ny)
            
cnt, cnt2 = 0, 0

for y in range(N):
    for x in range(N):
        if visited[x][y] == False:
            dfs(x,y)
            cnt += 1

for y in range(N):
    for x in range(N):
        if graph[x][y] == 'G':
            graph[x][y] = 'R'
visited = [[False] * N for _ in range(N)]

for y in range(N):
    for x in range(N):
        if visited[x][y] == False:
            dfs(x,y)
            cnt2 += 1

print(cnt, cnt2)
This post is licensed under CC BY 4.0 by the author.