๐Ÿ—๏ธ Algorithm/โน๏ธ SW Expert Academy [SWEA]

โน๏ธ[SW Expert Academy] [Python] [D4] [1249] ๋ณด๊ธ‰๋กœ

Dbswnstjd 2024. 3. 14. 00:52

๋ฌธ์ œ

https://swexpertacademy.com/main/code/problem/problemDetail.do?problemLevel=3&problemLevel=4&problemLevel=5&contestProbId=AV15QRX6APsCFAYD&categoryId=AV15QRX6APsCFAYD&categoryType=CODE&problemTitle=&orderBy=INQUERY_COUNT&selectCodeLang=ALL&select-1=5&pageSize=10&pageIndex=1

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

ํ’€์ด

# 1249. [S/W ๋ฌธ์ œํ•ด๊ฒฐ ์‘์šฉ] 4์ผ์ฐจ - ๋ณด๊ธ‰๋กœ
from collections import deque
dx = [0,0,1,-1]
dy = [1,-1,0,0]

def bfs(x, y):
    q = deque([(x,y)])
    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 < N:
                if dist[x][y] + graph[nx][ny] < dist[nx][ny]: // ๋‹ค์Œ ๊ฐ€์•ผํ•  ๊ฑฐ๋ฆฌ๊ฐ€ ์ง€๊ธˆ๊นŒ์ง€ ๊ฑฐ๋ฆฌ + ๊ทธ๋ž˜ํ”„์˜ ํฌ๊ธฐ ๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ
                    dist[nx][ny] = dist[x][y] + graph[nx][ny]
                    q.append((nx, ny))

for test_case in range(1, int(input())+1):
    N = int(input())
    graph = [list(map(int, input())) for _ in range(N)]
    dist = [[1e9]*N for _ in range(N)]
    dist[0][0] = graph[0][0]

    bfs(0,0)
    print("#{} {}".format(test_case, dist[N-1][N-1]))

BFS์™€ ๋‹ค์ต์ŠคํŠธ๋ผ ๋“ฑ์„ ์ด์šฉํ•ด์„œ ํ‘ธ๋Š” ์—ฌ๋Ÿฌ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์กด์žฌํ•œ๋‹ค. ๋‚˜๋Š” BFS๊ฐ€ ๊ฐ€์žฅ ํŽธํ•œ ๋ฐฉ๋ฒ•์ด์–ด์„œ ์‚ฌ์šฉํ–ˆ๋‹ค.