[파이썬]백준 10026 적록색약

Byeonghyeon Kim·2021년 3월 15일
0

알고리즘문제

목록 보기
33/93
post-thumbnail

링크

백준 10026 적록색약


dfs로 직점 탐색해가면서 풀었다.
dfs에 status라는 인자를 추가해 정상일때와 적록색약일때를 구분해서 방문처리를 해주었다.
공연히 같은일을 하는 함수를 두번호출한 것 같아서 status 인자 없이 한번에 두가지 경우를 계산해보려 노력했는데 방법이 떠오르지 않았다.


정답 코드

import sys
sys.setrecursionlimit(100000)

def dfs(r, c, color, status):
    if status == 'normal':
        normal_visit[r][c] = 1
        for i in range(4):
            nr = r + dr[i]
            nc = c + dc[i]
            if 0 <= nr < N and 0 <= nc < N:
                if normal_visit[nr][nc] == 0 and rgb[nr][nc] == color:
                    dfs(nr, nc, color, 'normal')

    if status == 'abnormal':
        abnormal_visit[r][c] = 1
        for i in range(4):
            nr = r + dr[i]
            nc = c + dc[i]
            if 0 <= nr < N and 0 <= nc < N:
                if color == 'R' or color == 'G':
                    if abnormal_visit[nr][nc] == 0 and (rgb[nr][nc] == 'R' or rgb[nr][nc] == 'G'):
                        dfs(nr, nc, color, 'abnormal')
                else:
                    if abnormal_visit[nr][nc] == 0 and rgb[nr][nc] == color:
                        dfs(nr, nc, color, 'abnormal')

N = int(input())
rgb = [input() for _ in range(N)]

normal_visit = [([0] * N) for _ in range(N)]
abnormal_visit = [([0] * N) for _ in range(N)]
normal_cnt = abnormal_cnt = 0

dr = [-1, 0, 1, 0]
dc = [0, 1, 0, -1]

for i in range(N):
    for j in range(N):
        if normal_visit[i][j] == 0:
            dfs(i, j, rgb[i][j], 'normal')
            normal_cnt += 1
        if abnormal_visit[i][j] == 0:
            dfs(i, j, rgb[i][j], 'abnormal')
            abnormal_cnt += 1

print(normal_cnt, abnormal_cnt)

알게된 것👨‍💻

  • 조건을 걸기 위해 함수에 인자를 추가하는 것을 두려워하지 말자
profile
자기 주도 개발전 (개발, 발전)

0개의 댓글