세상의 모든 알고리즘
[백준 2178번 python] 미로 탐색 문제 본문
https://www.acmicpc.net/problem/2178
이전 이코테 책에 수록된 문제가 백준에 있어 다시한번 풀어보는 시간을 갖게 되었습니다.
책을 통해 문제를 풀때는 시간제한이 없어 쉽게 느껴졌지만, 이번 문제 같은경우 1초의 시간제한이 있어
input() 함수를 -> 좀더 시간이 효율적인 sys.stdin.readline() 함수로 교체해서 사용했습니다.
import sys
input = sys.stdin.readline
from collections import deque
n,m = map(int,input().split())
graph = []
for _ in range(n):
graph.append(list(map(int,input().rstrip())))
dx = [0,0,1,-1]
dy = [-1,1,0,0]
def bfs(x,y):
q = deque()
q.append((x,y))
while q:
a,b = q.popleft()
for i in range(4):
nx = a + dx[i]
ny = b + dy[i]
if nx>= 0 and nx <n and ny >= 0 and ny <m :
if graph[nx][ny] == 1:
graph[nx][ny] = graph[a][b] + 1
q.append((nx,ny))
return graph[n-1][m-1]
print(bfs(0,0))
알게된 점
미로를 sys.stdin.readline()함수로 한줄단위로 받아들일때 rstrip()함수를 사용하지 않으면 개행문자가 같이 입력되어 오류가 발생합니다.
'python' 카테고리의 다른 글
[백준 2667 python] 단지번호 붙이기 (0) | 2021.11.04 |
---|---|
[백준 18352번 python] 특정 거리의 도시 찾기 (0) | 2021.11.04 |
[백준 7576번 python] 토마토 문제 (0) | 2021.11.04 |
[이것이코딩테스트다 Python] 미로 탈출 (0) | 2021.11.03 |
[백준 1260번 python] DFS와 BFS 문제 (0) | 2021.11.01 |