본문 바로가기

개발/algorithm

[백준 2178번] 미로 탐색 - python

문제 링크

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

 

2178번: 미로 탐색

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

www.acmicpc.net

풀이 

- bfs 문제 

- bfs로 (0,0)에서 (n-1,m-1)까지의 최단 거리를 구해준다. 

from collections import deque 

dx = [ 1, -1, 0, 0]
dy = [ 0, 0, 1, -1]

def bfs(a,b):
  visited[a][b] = 1

  q = deque()
  q.append((a,b))

  while q:
    x, y = q.popleft()

    for i in range(4):
      nx = x + dx[i]
      ny = y + dy[i]

      if 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1 and visited[nx][ny] == 0:
        
        visited[nx][ny] = 1
        # 거리 갱신 
        graph[nx][ny] = graph[x][y] + 1 
        q.append((nx,ny))
      
n, m = map(int,input().split())

graph = []
visited = [ [0] * (m) for _ in range(n)]

for _ in range(n):
  graph.append(list(map(int,input())))

bfs(0,0)
print(graph[n-1][m-1])

'개발 > algorithm' 카테고리의 다른 글