https://www.acmicpc.net/problem/2178
문제풀이
import sys
input=sys.stdin.readline
from collections import deque
def bfs(x,y):
dx=[0,1,-1,0] #인접한 상하좌우 확인
dy=[1,0,0,-1]
queue=deque()
queue.append((x,y)) #처음 방문하고 시작
while queue:
x,y=queue.popleft() #한번 방문한 곳은 삭제
for i in range(0,4):
nx=x+dx[i]
ny=y+dy[i]
if nx>=0 and nx<N and ny>=0 and ny<M: #인덱스 범위 조건을 제일 우선 확인하도록 해야함
if matrix[nx][ny]!=0 and matrix[nx][ny]==1:
matrix[nx][ny]=matrix[x][y]+1 #지금까지 지나온 곳+1을 해서 다음 칸에 저장
queue.append((nx,ny)) #다음 반복문을 수행하기 위해서 넣어주기
else:
continue
else:
continue
return matrix[N-1][M-1]
N,M=map(int,input().split())
matrix=[]
for _ in range(0,N):
matrix.append(list(map(int,input().strip())))
print(bfs(0,0))
'코딩테스트 > 백준' 카테고리의 다른 글
[백준] #1138 한 줄로 서기 (python) (0) | 2024.05.16 |
---|---|
[백준] #2667 단지번호붙이기 (python) (0) | 2024.05.16 |
[백준] #2578 빙고 (python) (0) | 2024.05.11 |
[백준] #1213 팰린드롬 만들기 (python) (0) | 2024.05.04 |
[백준] #17413 단어 뒤집기2 (python) (0) | 2024.04.30 |