최대 1 분 소요

문제링크 : https://www.acmicpc.net/problem/21736

전형적인 BFS 문제이며, I가 있는 위치를 deque()를 통해 관리한다.

그 후 deque의 원소가 0이 될 때까지 BFS를 시행하며

이때 P를 만난다면, cnt를 하나씩 증가한다.

import sys
from collections import deque

def BFS():
    cnt = 0
    while to_visits:
        current_row, current_col = to_visits.popleft()
        for idx in range(4):
            next_row, next_col = current_row + dx[idx], current_col + dy[idx]
            if 0<=next_row < N and 0<=next_col < M and matrix[next_row][next_col] not in ['X', 'I']:
                if matrix[next_row][next_col] == 'P':
                    cnt += 1
                to_visits.append([next_row, next_col])
                matrix[next_row][next_col] = 'I'
    return cnt



N, M = map(int, input().split())
matrix = []
dx = [1, -1, 0, 0]
dy = [0, 0, 1, -1]
for _ in range(N):
    tmp = list(input())
    matrix.append(tmp)

to_visits = deque()
for i in range(N):
    for j in range(M):
        if matrix[i][j] == 'I':
            to_visits.append([i, j])

answer = BFS()
if answer == 0:
    print('TT')
else:
    print(answer)

카테고리:

업데이트:

댓글남기기