BFS & DFS
[Python] 백준 11559번 : Puyo Puyo
Algomalgo
2024. 6. 20. 16:00
728x90
<접근 방법>
[1] 배열 arr을 만들고, 빈공간 '.'이 아닐 경우 bfs를 통해 같은 색의 뿌요들이 4개 이상 모여있는지 확인
[2] 4개 이상 모여있을 경우, 뿌요들을 터뜨려 빈공간 '.'으로 변경 + 터진 이력이 있으므로 flag = True로 변경
[3] 중
[4] 터진 이력이 없을 경우, flag는 그대로 False이므로 연쇄 중단
from collections import deque
def bfs(m, n):
global flag
q = deque()
q.append((m, n))
temp = [(m, n)] # 같은 색깔 연결 정보
visited[m][n] = 1 # 방문 처리 주의!
while q:
ci, cj = q.popleft()
for di, dj in ((-1, 0), (0, 1), (1, 0), (0, -1)):
ni = ci + di
nj = cj + dj
if 0<=ni<12 and 0<=nj<6 and arr[ni][nj] == arr[m][n] and not visited[ni][nj]:
q.append((ni, nj))
visited[ni][nj] = 1
temp.append((ni, nj))
# 연결된 뿌요가 4개 이상일 경우, '.'으로 변경
if len(temp) > 3:
for a, b in temp:
arr[a][b] = '.'
flag = True
arr = [list(input()) for _ in range(12)]
count = 0
while True:
flag = False
visited = [[0]*6 for _ in range(12)]
for i in range(12):
for j in range(6):
if arr[i][j] == '.':
continue
bfs(i, j) # 뿌요일 경우 bfs진행을 통해 연결 정보 확인
if not flag: # 폭발 이력이 없으면 연쇄 폭발 종료
break
count += 1 # 연쇄 + 1
# 중력
for j in range(6):
for i in range(11, 0, -1):
if arr[i][j] == '.':
for k in range(i, -1, -1):
if arr[k][j] != '.':
arr[i][j], arr[k][j] = arr[k][j], arr[i][j]
break
else:
break
print(count)
이해가 되지 않는 부분이 있으면 질문 주세요. 감사합니다.
728x90