ποΈΒ solution
import sys
from collections import deque
def solution():
N, M, P = map(int, sys.stdin.readline().split())
scores = [0] * (P + 1)
dy = [0, 0, 1, -1] # direction of search
dx = [1, -1, 0, 0]
p_list = [0] + list(map(int, sys.stdin.readline().split())) # for matching index with player num
graph = [[0]*M for _ in range(N)]
player_q = [deque() for _ in range(P+1)] # for matching index with player num
# 1) player dict μ΄κΈ°ν
for i in range(N):
tmp = sys.stdin.readline().rstrip()
for j in range(M):
if tmp[j] == ".":
continue
elif tmp[j] == "#":
graph[i][j] = -1
else:
now = int(tmp[j])
graph[i][j] = now
player_q[now].append([i, j])
scores[now] += 1
# 2) κ°λ³ player νμ
turn = True
while turn:
turn = False
for player in range(1, P+1):
if not player_q[player]: # μ΄λ―Έ νμμ΄ μ’
λ£λ νλ μ΄μ΄ ν΄ μ€ν΅
continue
q = player_q[player]
for _ in range(p_list[player]):
if not q: # λͺ¨λ νλ μ΄μ΄λ€μ΄ 1κ° μ΄μ μμ νμ₯ λͺ»νλλ° μ΅λ νμ κΉμ΄κ° λ§€μ° ν° κ²½μ°, νλκ² λλ€
break
for _ in range(len(q)):
vy, vx = q.popleft()
for i in range(4):
ny = dy[i] + vy
nx = dx[i] + vx
if -1 < ny < N and -1 < nx < M and graph[ny][nx] == 0:
graph[ny][nx] = player
scores[player] += 1
q.append([ny, nx])
turn = True
print(*scores[1:])
if __name__ == "__main__":
solution()
π‘Β idea
- 1) BFS
- 1-1)
grid
μ΄κΈ°ν
- 루ν λ΄λΆμ νμ
μΊμ€ν
ν¨μ νΈμΆ λ°©μ§λ₯Ό μν΄ λ¬Έμμ΄ μ
λ ₯μ μ μλ‘ λ³ν
- λμμ κ°λ³ νλ μ΄μ΄μ μ΄κΈ° μμ μμΉλ₯Ό κ°λ³ νμ μ½μ
(
player_q
)
- νλ μ΄μ΄ μ μ μ΄κΈ°ν λ° μ
λ°μ΄νΈ
- 1-2)
BFS
μν
- λΌμ΄λ ꡬν:
while loop
- κ°λ³ νλ μ΄μ΄ ν΄, νμ κΉμ΄ μ ν, 1ν νμ λ° λμ νμ ꡬν:
for-loop
- κ°λ³ νλ μ΄μ΄ ν΄:
for player in range(1, P+1):
- νμ κΉμ΄ μ ν:
for _ in range(p_list[player]):
- λͺ¨λ νλ μ΄μ΄κ° 1κ° μ΄μ μμ νμ₯ λΆκ°ν μν© and μ΅λ νμ κΉμ΄ λ§€μ° ν° κ²½μ°
- νμ κΉμ΄ μ ν 루νλ₯Ό νλκ² λκΈ° λλ¬Έμ μκ° μ΄κ³Ό λ°μ
- νκ° λΉμλ€λ©΄ 루ν νμΆνλλ‘ μ½λ μΆκ° νμ:
break if not q
- 1ν νμ λ° λμ νμ ꡬν:
for _ in range(len(q)):
π€Β λ°λ‘
""" λ°λ‘ μΌμ΄μ€ """
4 10 4
1000000000 1 100 99999
1#........
#.........
2#.......#
3#......#4
Leave a comment