++/자료구조&알고리즘

[baekjoon] 10026. 적록색약

writtenbyrla 2024. 1. 16. 19:40

✅ 문제

 

 

💡 문제 이해

1. 섬 개수 구하기와 비슷하지만 R, G, B로 섬 구분 
2. 적록색약의 경우 R, G 구분이 안가므로 R+G / B로 구분
3. 각 구역 수 count 후 출력

 


 

✅ 나의 코드

💡 문제 풀이 Point

1. 적록색약의 여부를 isblind로 구분해서 dfs 탐색시 같이 넘김
2. dfs 탐색 시 
  2-1) 적록색약인 경우 B인 경우와 B가 아닌 경우를 나누어서 탐색
  2-2) 적록색약이 아닌 경우 일반적인 dfs 탐색

 

import sys
input = sys.stdin.readline
sys.setrecursionlimit(10000)

def dfs(x, y, color, isblind):
    for i in range(4):
        nx = x+dx[i]
        ny = y+dy[i]

        if 0 <= nx < n and 0 <= ny < n and not visited[nx][ny]:
            # 적록색약일 경우
            if isblind == 'blind':
                if color != 'B' and arr[nx][ny] != 'B':
                    visited[nx][ny] = True
                    dfs(nx, ny, color, isblind)
                elif color == 'B' and arr[nx][ny] == 'B':
                    visited[nx][ny] = True
                    dfs(nx, ny, color, isblind)
                else:
                    continue

            # 적록색약 아닐 경우
            else:
                if color == arr[nx][ny]:
                    visited[nx][ny] = True
                    dfs(nx, ny, color, isblind)
    return


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

n = int(input())
visited = [[False] * n for _ in range(n)]
arr = [list(input().rstrip()) for _ in range(n)]

count = 0
blind_count = 0

# 적록색약 아닐 경우
for i in range(n):
    for j in range(n):
        if not visited[i][j]:
            dfs(i, j, arr[i][j], '!blind')
            count += 1

# 적록 색약일 경우
# visitied 배열 초기화
visited = [[False] * n for _ in range(n)]
for i in range(n):
    for j in range(n):
        if not visited[i][j]:
            dfs(i, j, arr[i][j], 'blind')
            blind_count +=1

print(count, blind_count)

'++ > 자료구조&알고리즘' 카테고리의 다른 글

[baekjoon] 2212. 센서  (0) 2024.01.18
[baekjoon] 7562. 나이트의 이동  (0) 2024.01.16
[leetcode] 543. Diameter of Binary Tree  (0) 2024.01.12
[baekjoon] 2493. 탑  (1) 2024.01.09
[baekjoon] 4949. 균형잡힌 세상  (2) 2024.01.09