Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

세상의 모든 알고리즘

[백준 2178번 python] 미로 탐색 문제 본문

python

[백준 2178번 python] 미로 탐색 문제

952hi 2021. 11. 4. 16:02

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

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

 

이전 이코테 책에 수록된 문제가 백준에 있어 다시한번 풀어보는 시간을 갖게 되었습니다.

책을 통해 문제를 풀때는 시간제한이 없어 쉽게 느껴졌지만, 이번 문제 같은경우 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()함수를 사용하지 않으면 개행문자가 같이 입력되어 오류가 발생합니다.