백준

[백준] 21736번: 헌내기는 친구가 필요해(파이썬)

초코바나나쉐이크 2024. 12. 12. 01:25

https://www.acmicpc.net/problem/21736

 

많이 풀어봤던 BFS 유형이었다~

from collections import deque

N,M = map(int,input().split()) #N:행, M:열
graph = [  list(input())  for _ in range(N)]
dx = [0, -1, 0, 1]
dy = [1, 0, -1, 0] 


def bfs(i,j):
    queue = deque()
    queue.append((i,j))
    result = 0
    while queue: #queue가 빌 때까지 반복
        
       
        x,y = queue.popleft()
        for i in range(4):
            cur_x,cur_y = x+dx[i], y+dy[i]
           
            if cur_x < 0 or cur_x >= N or cur_y < 0 or cur_y >= M or graph[cur_x][cur_y] == 'X' or graph[cur_x][cur_y] == 'I':

                pass
            else:
                queue.append((cur_x,cur_y))
                if graph[cur_x][cur_y] == 'P':
                    result += 1
                graph[cur_x][cur_y] = 'I'
    return result

for i in range(N):
    for j in range(M):
        if graph[i][j] == 'I':
            x,y = i,j
result = bfs(x,y)

if result == 0:
    print('TT')
else:
    print(result)