백준 14940 python [쉬운 최단거리]

인지용·2025년 3월 24일
0

알고리즘

목록 보기
46/46
post-thumbnail

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

import sys
from collections import deque

# with open("./data.txt", "r") as file:
#     def input():
#         return file.readline().strip()
    
def input():
    return sys.stdin.readline()

def bfs(y, x):
    Q = deque()
    Q.append((y, x))
    visited[y][x] = True
    arr[y][x] = 0
    
    while Q:
        a, b = Q.popleft()
        
        for i in range(4):
            ny = a + moveY[i]
            nx = b + moveX[i]
            
            if(0 > ny or ny >= n or 0 > nx or nx >= m):
                continue
        
            if(visited[ny][nx] == False and arr[ny][nx] == 1):
                arr[ny][nx] = arr[a][b] + 1
                visited[ny][nx] = True
                Q.append((ny, nx))
    

moveX = [1, 0, -1, 0]
moveY = [0, -1, 0, 1]

n, m = map(int, input().split(" "))
arr = []
visited = [[False] * m for _ in range(n)]

for i in range(n):
    arr.append(list(map(int, input().split(" "))))

for y in range(n):
    for x in range(m):
        if(arr[y][x] == 2 and visited[y][x] == False):
            bfs(y, x)

for y in range(n):
    for x in range(m):
        if(visited[y][x] == False and arr[y][x] != 0):
            arr[y][x] = -1

for y in range(n):
    print(" ".join(map(str, arr[y])))

먼저 2로 시작되는 출발점을 찾고
출발점에서 연결된 애들만 전부 값을
이전 노드값 + 1로 업데이트 해주자.

그리고 다시 전체를 노드를 탐색하면서 방문하지 않은 애들을 -1로 변경해주면 된다.

(첫번째 탐색에서 방문하지 않은 애들은 2와 연결되지 못했다는 의미니까 -1로 변경하면 된다)
profile
한-줄

0개의 댓글