전공/백준
21736
yha97
2023. 7. 25. 22:53
날짜 : 2023. 07. 25
사용 언어 : python
문제
코드
import sys
from collections import deque
def bfs(r, c):
queue = deque()
queue.append([r, c])
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
visited[r][c] = True
cnt = 0
while queue:
x, y = queue.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx in range(n) and ny in range(m) and not visited[nx][ny] and graph[nx][ny] != 'X':
visited[nx][ny] = True
queue.append([nx, ny])
if graph[nx][ny] == 'P': cnt += 1 # 사람 만남
return cnt
n, m = map(int, sys.stdin.readline().split()) # 행, 열
graph = list()
visited = [[False] * m for _ in range(n)]
res = 0
for _ in range(n):
graph.append(''.join(sys.stdin.readline().rstrip().split()))
for i in range(n):
for j in range(m):
if graph[i][j] == 'I':
res = bfs(i, j)
break
else: continue
break
if res == 0:
print("TT")
else:
print(res)
풀이
- BFS로 풀이한다.
- 카운트했을 때 수가 0인 케이스와 아닌 케이스에 대해 조건문을 달아 값을 다르게 출력
알게된 점
-
참고 사이트
-