<내 코드>
- DFS
import sys
sys.setrecursionlimit(10000)
def dfs(x, y, type):
done.append((x, y))
# 4방향 확인
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if(0 <= nx < N) and (0 <= ny < N) and ((nx, ny) not in done):
# 정상인
if type == 0 and colors[nx][ny] == colors[x][y]:
dfs(nx, ny, 0)
# 적록색맹
elif type == 1 and colors[nx][ny] == colors[x][y]:
dfs(nx, ny, 1)
N = int(input())
colors = [list(input()) for _ in range(N)]
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
# 정상인인 경우
done = []
cnt_1 = 0
for i in range(N):
for j in range(N):
if (i, j) not in done:
dfs(i, j, 0)
cnt_1 += 1
# 적록색맹인 경우
for i in range(N):
for j in range(N):
if colors[i][j] == 'G':
colors[i][j] = 'R'
done = []
cnt_2 = 0
for i in range(N):
for j in range(N):
if (i, j) not in done:
dfs(i, j, 1)
cnt_2 += 1
print(cnt_1, cnt_2)
DFS로 풀 때 런타임 에러 방지하기 위해 sys.setrecursionlimit(10000) 설정해준다. 그리고 type 값에 따라 정상인과 색약의 상태를 구분해 탐색한다. 시간을 조금 더 줄여보는 방법을 생각해봐야겠다.
- BFS
from collections import deque
def bfs(x, y):
queue.append((x, y))
done.append((x, y))
while queue:
curr = queue.popleft()
for i in range(4):
nx = curr[0] + dx[i]
ny = curr[1] + dy[i]
if (0 <= nx < N) and (0 <= ny < N) and ((nx, ny) not in done):
if colors[nx][ny] == colors[curr[0]][curr[1]]:
queue.append((nx, ny))
done.append((nx, ny))
N = int(input())
colors = [list(input()) for _ in range(N)]
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
# 정상인인 경우
queue = deque()
done = []
cnt_1 = 0
for i in range(N):
for j in range(N):
if (i, j) not in done:
bfs(i, j)
cnt_1 += 1
# 적록색맹인 경우
for i in range(N):
for j in range(N):
if colors[i][j] == 'G':
colors[i][j] = 'R'
queue = deque()
done = []
cnt_2 = 0
for i in range(N):
for j in range(N):
if (i, j) not in done:
bfs(i, j)
cnt_2 += 1
print(cnt_1, cnt_2)
반응형
'알고리즘 문제풀기 > 백준 - Python' 카테고리의 다른 글
[백준 7562] 나이트의 이동 - Python (BFS) (0) | 2020.09.04 |
---|---|
[백준 2468] 안전 영역 - Python (브루트포스, DFS) (0) | 2020.09.03 |
[백준 1987] 알파벳 - Python (DFS, 백트래킹) (0) | 2020.09.03 |
[백준 8958] OX 퀴즈 - Python (문자열) (0) | 2020.09.02 |
[백준 2667] 단지번호 붙이기 - Python (그래프, BFS) (0) | 2020.09.01 |