Updated:

πŸ–οΈΒ 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