본문 바로가기
백준

적록색약 - 10026번

by 청원뿔세포 2022. 10. 4.

bfs로 문제를 해결하였다.

 

graph를 2개, bfs함수를 3개를 만들어서 사용했다.

한 for 루프 안에서, 정상인의 결과를 구하고, 적록색약인 사람의 결과를 따로 구해줬다.

import sys
from collections import deque


t = int(input())
graph = [[0] * 101 for _ in range(101)]
special_graph = [[0] * 101 for _ in range(101)]
d = [[1, 0], [-1, 0], [0, 1], [0, -1]]
for y in range(t):
  inn = sys.stdin.readline()
  for x in range(t):
    graph[y][x] = inn[x]
    special_graph[y][x] = inn[x]



def bfs(x, y, color):
  q = deque([(x, y, color)])
  while q:
    x, y, color = q.popleft()

    for i in range(4):
      nx = x + d[i][0]
      ny = y + d[i][1]

      if 0 <= nx < t and 0 <= ny < t and graph[ny][nx] == color:
        graph[ny][nx] = '0'
        q.append((nx, ny, color))


def red_green_bfs(x, y, color):
  q = deque([(x, y, color)])
  while q:
    x, y, color = q.popleft()

    for i in range(4):
      nx = x + d[i][0]
      ny = y + d[i][1]

      if 0 <= nx < t and 0 <= ny < t and (special_graph[ny][nx] == 'R'
                                          or special_graph[ny][nx] == 'G'):
        special_graph[ny][nx] = '0'
        q.append((nx, ny, color))

def blue_bfs(x, y, color):
  q = deque([(x, y, color)])
  while q:
    x, y, color = q.popleft()

    for i in range(4):
      nx = x + d[i][0]
      ny = y + d[i][1]

      if 0 <= nx < t and 0 <= ny < t and special_graph[ny][nx] == color:
        special_graph[ny][nx] = '0'
        q.append((nx, ny, color))

normal_ans = 0
special_ans = 0
for y in range(t):
  for x in range(t):
    if graph[y][x] == 'R':
      normal_ans += 1
      bfs(x, y, 'R')
    elif graph[y][x] == 'G':
      normal_ans += 1
      bfs(x, y, 'G')
    elif graph[y][x] == 'B':
      normal_ans += 1
      bfs(x, y, 'B')
    if special_graph[y][x] == 'R' or special_graph[y][x] == 'G':
        special_ans += 1
        red_green_bfs(x,y,special_graph[y][x])
    elif special_graph[y][x] == 'B':
        special_ans += 1
        blue_bfs(x,y,'B')
        
print(normal_ans, special_ans)

'백준' 카테고리의 다른 글

나이순 정렬 - 10814번  (0) 2022.10.09
영화감독 숌 - 1436번  (0) 2022.10.05
미로탐색 - 2178 번  (0) 2022.10.04
유기농 배추 - 1012번  (0) 2022.10.04
N과 M (2) - 15650 번  (0) 2022.10.03

댓글