본문 바로가기

알고리즘/백준

백준 2178번 : 미로 탐색(S1)

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

 

내 코드

from collections import deque
import sys
input = sys.stdin.readline

def main():
    n, m = map(int, input().split())
    
    maze = [list(input().strip()) for _ in range(n)]
    visited = [[False] * m for _ in range(n)]
    
    bfs(maze, visited)
    
    print(maze[n-1][m-1])

def bfs(graph, visited):
    queue = deque()
    queue.append((0, 0))
    
    rows = len(graph)
    cols = len(graph[0])
    
    while queue:
        x, y = queue.popleft()
        
        if visited[x][y]:
            continue

        visited[x][y] = True
        
        if x - 1 >= 0:
            if graph[x-1][y] == '1' and not visited[x-1][y]:
                queue.append((x-1, y))
                # 현재 칸의 값(문자열을 정수로 변환 후) + 1을 기록
                graph[x-1][y] = str(int(graph[x][y]) + 1)
                
        if x + 1 < rows:
            if graph[x+1][y] == '1' and not visited[x+1][y]:
                queue.append((x+1, y))
                graph[x+1][y] = str(int(graph[x][y]) + 1)
                
        if y - 1 >= 0:
            if graph[x][y-1] == '1' and not visited[x][y-1]:
                queue.append((x, y-1))
                graph[x][y-1] = str(int(graph[x][y]) + 1)
                
        if y + 1 < cols:
            if graph[x][y+1] == '1' and not visited[x][y+1]:
                queue.append((x, y+1))
                graph[x][y+1] = str(int(graph[x][y]) + 1)

if __name__ == "__main__":
    main()

1. 다른 코드를 보니 방향을 리스트로 설정해서 쉽게 푸는 듯 하자 좋은 방법이다.

2. 예외처리를 try except로 하지 말고 if문으로 처리하는게 낫다.

 

풀이 시간