백준 10026번: 적록색약

Seungil Kim·2021년 9월 7일
1

PS

목록 보기
31/206

적록색약

백준 10026번: 적록색약

아이디어

bfs. 근처에 같은 색이 존재하면 큐에 넣고 탐색. 적색 녹색을 구분하지 않게 하기 위해 R을 전부 G로 변경하고 다시 탐색했다.

코드

from collections import deque

N = int(input())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
graph = [input() for _ in range(N)]
visited = [[False] * N for _ in range(N)]


def bfsRGB():
    count = 0
    q = deque()
    for i in range(N):
        for j in range(N):
            if visited[i][j] is False:
                count += 1
                visited[i][j] = True
                q.append((i, j))
                color = graph[i][j]
                while q:
                    row, col = q.popleft()
                    for k in range(4):
                        nextRow = row + dy[k]
                        nextCol = col + dx[k]
                        if nextRow < 0 or nextRow >= N or nextCol < 0 or nextCol >= N:
                            continue
                        elif graph[nextRow][nextCol] != color:
                            continue
                        elif visited[nextRow][nextCol] is True:
                            continue
                        else:
                            visited[nextRow][nextCol] = True
                            q.append((nextRow, nextCol))
    return count


a = bfsRGB()
visited = [[False] * N for _ in range(N)]
for i in range(N):
    graph[i] = graph[i].replace('R', 'G')
b = bfsRGB()
print(f"{a} {b}")

여담

맨날 너무 쉬운것만 골라푸는듯.

profile
블로그 옮겼어용 https://ks1ksi.io/

2개의 댓글

comment-user-thumbnail
2021년 9월 8일

골드 문제를 풀 수 있는 두뇌를 가진 남자...

1개의 답글