λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/boj

BOJ 10026 - 적둝색약

by HandHand 2021. 6. 9.

문제

λ°±μ€€ 온라인 저지 - 10026번

풀이 κ³Όμ •

μž…λ ₯된 board 의 크기가 크지 μ•ŠμœΌλ―€λ‘œ DFS 탐색을 톡해 λͺ¨λ“  ꡬ간을 μ°Ύμ•„μ€¬μŠ΅λ‹ˆλ‹€.

색맹이 μžˆλŠ” μ‚¬λžŒκ³Ό μ—†λŠ” μ‚¬λžŒμ€ 탐색 μ œμ•½μ‘°κ±΄μ΄ λ‹€λ₯΄κΈ° λ•Œλ¬Έμ— 각각 visit 배열을 λ§Œλ“€μ–΄μ„œ λ”°λ‘œ 탐색을 μˆ˜ν–‰ν–ˆμŠ΅λ‹ˆλ‹€.

2번의 DFS λ₯Ό μˆ˜ν–‰ν•΄λ„ 총 μ‹œκ°„ λ³΅μž‘λ„κ°€ O(2n) 이기 λ•Œλ¬Έμ— μ‹œκ°„ 내에 μˆ˜ν–‰μ΄ κ°€λŠ₯ν–ˆμŠ΅λ‹ˆλ‹€.

μ½”λ“œ


import sys

sys.setrecursionlimit(10**6)


N = int(input())
board = []
for _ in range(N):
    board.append(list(sys.stdin.readline()[:-1]))

dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]


def dfs(x, y, visit, decision):
    visit[x][y] = 1

    for i in range(4):
        nx, ny = x + dx[i], y + dy[i]
        if 0 <= nx < N and 0 <= ny < N:
            if not visit[nx][ny] and board[nx][ny] in decision:
                dfs(nx, ny, visit, decision)


def solution():
    normal_visit = [[0]*N for _ in range(N)]
    sick_visit = [[0]*N for _ in range(N)]

    ans = [0, 0]
    for r in range(N):
        for c in range(N):
            if not normal_visit[r][c]:
                dfs(r, c, normal_visit, [board[r][c]])
                ans[0] += 1
            if not sick_visit[r][c]:
                if board[r][c] == 'R' or board[r][c] == 'G':
                    dfs(r, c, sick_visit, ['R', 'G'])
                else:
                    dfs(r, c, sick_visit, ['B'])
                ans[1] += 1

    return ' '.join(map(str, ans))


print(solution())
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€