새소식

알고리즘/그래프

[백준 14940] 쉬운 최단거리 (파이썬 풀이)

  • -

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

 

14940번: 쉬운 최단거리

지도의 크기 n과 m이 주어진다. n은 세로의 크기, m은 가로의 크기다.(2 ≤ n ≤ 1000, 2 ≤ m ≤ 1000) 다음 n개의 줄에 m개의 숫자가 주어진다. 0은 갈 수 없는 땅이고 1은 갈 수 있는 땅, 2는 목표지점이

www.acmicpc.net

제출코드

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

direction = [(-1,0),(1,0),(0,-1),(0,1)]
n,m = map(int,input().split())
arr = list(input().split() for _ in range(n))
visited = [[False]*m for _ in range(n)]
ans = [[0]*m for _ in range(n)]
for i in range(n):
    for j in range(m):
        if arr[i][j]=="2":
            visited[i][j] = True
            q = deque([(i,j)])

while q:
    x, y = q.popleft()
    for dx, dy in direction:
        nx = x+dx
        ny = y+dy

        if 0<=nx<n and 0<=ny<m and arr[nx][ny]=="1" and not visited[nx][ny]:
            q.append((nx,ny))
            visited[nx][ny] = True
            ans[nx][ny]= ans[x][y]+1

for i in range(n):
    for j in range(m):
        if not visited[i][j] and arr[i][j]=="1":
            print(-1,end=" ")
        else:
            print(ans[i][j], end=" ")
    print()

대표적인 BFS 문제.

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.