CodingTest/Baekjun Online Judge

[ BOJ / 파이썬 ] 10026 적록색약

EEOOOO 2022. 8. 16. 22:07

/  정답 코드  /

import sys
input = sys.stdin.readline
from collections import deque

# 우 하 좌 상
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]

n = int(input())

colors = [list(input().strip()) for _ in range(n)]

answer = []
for k in range(2):
  visited = [[False]*n for _ in range(n)]
  result = 0
  for i in range(n):
    for j in range(n):
      if not visited[i][j]:
        visited[i][j] = True
        q = deque([(i,j)])
        result += 1

        while q:
          x, y = q.popleft()
          currentColor = colors[x][y]
          for direction in range(4):
            nx = x + dx[direction]
            ny = y + dy[direction]
            if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny]:
              if colors[nx][ny] == currentColor:
                visited[nx][ny] = True
                q.append((nx, ny))
              elif k == 1:
                if colors[nx][ny] == 'R' and currentColor == 'G':
                  visited[nx][ny] = True
                  q.append((nx, ny))
                elif colors[nx][ny] == 'G' and currentColor == 'R':
                  visited[nx][ny] = True
                  q.append((nx, ny))
                
  answer.append(result)

print(" ".join(list(map(str,answer))))

 

 

세상에.. 처음에 로직은 잘 짜고 진짜 바보같은 실수로 틀렸다..

index를 중첩해서 쓴 것이다. 무슨 말이냐면

이렇게..

세상에.. 부끄러운 실수다 정말.. 집중하자.

 

- 적록색약인 사람 아닌 사람을 구분하는 로직을 고민했는데, 케이스가 두 개뿐이라서

- 그냥 적록색약인 사람인 경우에 대해서 R,G를 동일 색상으로 처리하는 부분을 추가로 넣어주는 식으로 작성했다.

 

- 적록색약인 경우에는 R과 G중 하나만 선택해서 맵을 업데이트해서 다시 확인한다던지의 방법도 괜찮을 것 같다. N이 100개뿐이므로. 이 경우에는 위의 K기준 For문을 함수로 처리해서 각각의 맵을 넣어서 결과를 리턴하는 식으로 구현하면 되겠다.