https://www.acmicpc.net/problem/11559
bfs๋ฅผ ์ ์ฌ์ฉํ๋ฉด ๋๋ ๋ฌธ์ .
์์ด๋์ด
์ ์ฒด ์ฝ๋
from collections import deque
dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
field_info = []
for _ in range(12):
field_info.append(list(input()))
def bfs(a, b, c):
global boom_flag
boom_list = []
deq = deque()
deq.append([a,b])
boom_list.append([a,b])
field_check[a][b] = True
n = 1
while deq:
x, y = deq.popleft()
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < 12 and 0 <= ny < 6:
if field_info[nx][ny] == c and not field_check[nx][ny]:
field_check[nx][ny] = True
deq.append([nx,ny])
boom_list.append([nx,ny])
n += 1
if n >= 4:
for b in boom_list:
field_info[b[0]][b[1]] = '.'
boom_flag = True
boom_count = 0
while True:
boom_flag = False
field_check = [[False] * 6 for _ in range(12)]
for i in range(12):
for j in range(6):
if field_info[i][j] != '.':
bfs(i,j,field_info[i][j])
for i in range(6):
rotate_queue = deque()
for j in range(11,-1,-1):
if field_info[j][i] != '.':
rotate_queue.append(field_info[j][i])
for j in range(11,-1,-1):
if rotate_queue:
field_info[j][i] = rotate_queue.popleft()
else:
field_info[j][i] = '.'
if not boom_flag:
break
else:
boom_count += 1
print(boom_count)
์ฝ๋ ์ค๋ช
1. bfs
for i in range(12):
for j in range(6):
if field_info[i][j] != '.':
bfs(i,j,field_info[i][j])
ํ๋์ ์๋ ๋ชจ๋ ์นธ์ ๋ํด ๋น์นธ('.')์ธ์ง ์๋์ง ํ์ธํ๊ณ ๋น์นธ์ด ์๋๋ฉด bfs๋ฅผ ์คํํ๋ค.
bfs ํจ์๋ ์๋์ ๊ฐ๋ค.
def bfs(a, b, c):
global boom_flag
boom_list = [] # ํฐํธ๋ฆด ์์น๋ฅผ ์ ์ฅ
deq = deque() # bfs๋ฅผ ์ํ ํ
deq.append([a,b])
boom_list.append([a,b])
field_check[a][b] = True
n = 1 #๋ฟ์ ๊ฐ์
while deq:
x, y = deq.popleft()
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < 12 and 0 <= ny < 6:
if field_info[nx][ny] == c and not field_check[nx][ny]:
field_check[nx][ny] = True
deq.append([nx,ny])
boom_list.append([nx,ny])
n += 1 #๋ธ๋ญ ๊ฐ์ +1
if n >= 4:
for b in boom_list:
field_info[b[0]][b[1]] = '.' #ํฐ์ง๊ณณ์ ๋น์นธ์ผ๋ก ๋ณ๊ฒฝ
boom_flag = True #ํฐ์ง
bfs ํ๋ฉด์ ์ ๋ ฅ๋ฐ์๋ ๋ธ๋ก์ ์๊น c์ ๊ฐ๊ณ ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ์นธ์ด๋ฉด ํ์ ์ถ๊ฐํด ์ค๋ค.
์ฐ๊ฒฐ๋ ๋ฟ์ ๊ฐ์๊ฐ 4๊ฐ ์ด์์ด๋ผ๋ฉด ๋น์นธ์ผ๋ก ๋ณ๊ฒฝํด ์ฃผ๊ณ , flag๋ฅผ true๋ก ๋ฐ๊ฟ์ค๋ค.
2. ๋ฟ์ ๋ด๋ฆฌ๊ธฐ
for i in range(6):
rotate_queue = deque()
for j in range(11,-1,-1):
if field_info[j][i] != '.':
rotate_queue.append(field_info[j][i])
for j in range(11,-1,-1):
if rotate_queue:
field_info[j][i] = rotate_queue.popleft()
else:
field_info[j][i] = '.'
๋น์นธ์ ์ฑ์์ฃผ๋ ์ฝ๋๋ค. ๊ฐ ์ด๋ง๋ค, ๋ฐ์์๋ถํฐ ์ค์บํ๋ฉฐ ๋ฟ์๋ฅผ rotate_queue์ ๋ฃ์ด์ฃผ๊ณ ,
๋ค์ ๋ฐ์์๋ถํฐ ์ฐจ๋ก๋๋ก ๋ฟ์๋ฅผ ์์์ค๋ค. ์ ๋ถ ๋ค ์๊ณ ๋ ๋ค ๋น์นธ์ผ๋ก ์ฑ์์ค๋ค.
'๐งฉ Problem Solving > [๋ฐฑ์ค]' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 9205 ๋งฅ์ฃผ ๋ง์๋ฉด์ ๊ฑธ์ด๊ฐ๊ธฐ (python ํ์ด์ฌ) (0) | 2023.04.09 |
---|---|
[๋ฐฑ์ค] 1759 ์ํธ๋ง๋ค๊ธฐ (python ํ์ด์ฌ) (0) | 2023.03.30 |
[๋ฐฑ์ค] 2583 ์์ญ ๊ตฌํ๊ธฐ(python ํ์ด์ฌ) (0) | 2023.03.16 |
[๋ฐฑ์ค] 14938 ์๊ฐ๊ทธ๋ผ์ด๋ (python ํ์ด์ฌ) (0) | 2022.09.10 |
[๋ฐฑ์ค]11660 ๊ตฌ๊ฐ ํฉ ๊ตฌํ๊ธฐ 5 (python ํ์ด์ฌ) (0) | 2022.08.19 |