DevYoon

[SWEA] 1249. ๋ณด๊ธ‰๋กœ (Python) ๋ณธ๋ฌธ

PS/SWEA

[SWEA] 1249. ๋ณด๊ธ‰๋กœ (Python)

gimewn 2022. 4. 11. 18:18

link ๐Ÿ”— https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV15QRX6APsCFAYD 

 

SW Expert Academy

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

swexpertacademy.com

 

1๏ธโƒฃ ์ถœ๋ฐœ์ง€ S(0, 0)์—์„œ ๋„์ฐฉ์ง€ G(N-1, N-1)๊นŒ์ง€ ๊ฐ€์žฅ ๋น ๋ฅธ ์‹œ๊ฐ„ ์•ˆ์— ๋ณต๊ตฌ ์™„๋ฃŒํ•˜๊ธฐ

2๏ธโƒฃ ๋„๋กœ๊ฐ€ ํŒŒ์—ฌ์ง„ ๊นŠ์ด์— ๋น„๋ก€ํ•˜์—ฌ ๋ณต๊ตฌ ์‹œ๊ฐ„ ์†Œ์š” ex) 1 โžก๏ธ 1 ์†Œ์š”

3๏ธโƒฃ 0 โžก๏ธ ๋ณต๊ตฌ ๋ถˆํ•„์š” (๊ทธ๋ƒฅ ๋”ํ•ด์ฃผ๊ธฐ)

 

from collections import deque

def bfs():
    q = deque()
    q.append((0, 0))
    while q:
        ny, nx = q.popleft()
        direct = [(-1, 0), (1, 0), (0, -1), (0, 1)]
        for i in range(4):
            dy = direct[i][0]+ny
            dx = direct[i][1]+nx
            if 0 <= dy < N and 0 <= dx < N:
                if visit[dy][dx] == 0: # ํ•œ ๋ฒˆ๋„ ๋“ค๋ฅธ ์  ์—†์œผ๋ฉด
                    visit[dy][dx] = 1
                    spend[dy][dx] = spend[ny][nx]+int(arr[dy][dx]) # ์‹œ๊ฐ„ ๋“ฑ๋ก
                    q.append((dy, dx))
                else: # ๋“ค๋ฅธ ์  ์žˆ์œผ๋ฉด
                    if spend[dy][dx] > spend[ny][nx]+int(arr[dy][dx]): # ์ตœ์†Œ ๊ฐฑ์‹ 
                        spend[dy][dx] = spend[ny][nx]+int(arr[dy][dx])
                        q.append((dy, dx))

t = int(input())

for tc in range(1, t+1):
    N = int(input())
    arr = [list(input()) for _ in range(N)]
    visit = [[0]*N for _ in range(N)]
    spend = [[0]*N for _ in range(N)]
    visit[0][0] = 1
    bfs()
    print(f'#{tc} {spend[N-1][N-1]}')

 

โœ๏ธ ๋ฉ”๋ชจ

  • ์Šต๊ด€์ฒ˜๋Ÿผ split() ์ผ๋‹ค๊ฐ€ ์•ˆ ๋˜๊ธธ๋ž˜ ๋ดค๋”๋‹ˆ 01234 ์ด๋Ÿฐ ์‹์œผ๋กœ ๋ถ™์–ด ์žˆ์—ˆ๋‹ค...๐Ÿ™ƒ
  • ์ตœ์†Œ ์‹œ๊ฐ„์ด๊ธธ๋ž˜ ์ƒ๊ฐ์—†์ด BFS๋กœ ํ’€์—ˆ๋”๋‹ˆ ๋‹ต์ด ์ œ๋Œ€๋กœ ๋‚˜์˜ค์ง€ ์•Š์•˜๋‹ค..ใ… 
  • ๊ทธ๋Ÿผ DFS๋กœ ํ’€์–ด๋ณผ๊นŒ? ํ–ˆ๋”๋‹ˆ ๋‹ต์€ ์ž˜ ๋‚˜์˜ค๋Š”๋ฐ ์‹œ๊ฐ„ ์ดˆ๊ณผ๐Ÿฅฒ
  • ๊ตฌ๊ธ€๋ง์˜ ๋„์›€์„ ๋ฐ›์•„ ๊ฐ ๋ธ”๋ก๋งˆ๋‹ค ๋ณต๊ตฌ์— ์†Œ์š”๋˜๋Š” ์‹œ๊ฐ„์„ ์ ์–ด์ค„ spend๋ฐฐ์—ด์„ ๋งŒ๋“ค์–ด ์ฃผ์—ˆ๊ณ , visit ๋ฐฐ์—ด์„ ์‚ฌ์šฉํ•ด์„œ ํ•œ ๋ฒˆ๋„ ๋“ค๋ฅธ ์  ์—†์œผ๋ฉด 1 ์ฒดํฌ ํ›„ spend ๋ฐฐ์—ด์— ๋“ฑ๋ก & q์— ๋„ฃ์–ด์ฃผ๊ธฐ, ๋“ค๋ฅธ ์  ์žˆ์œผ๋ฉด spend ๋ฐฐ์—ด ์ตœ์†Ÿ๊ฐ’ ๊ฐฑ์‹  ํ›„ q์— ๋„ฃ์–ด์ฃผ๋Š” ์‹์œผ๋กœ ํ–ˆ๋‹ค.
  • ๋„์ฐฉ์ง€๋Š” (N-1, N-1) ์ด๋ฏ€๋กœ spend ๋ฐฐ์—ด์˜ (N-1, N-1) ๊ฐ’์„ ์ถœ๋ ฅํ•ด์ฃผ๋ฉด ์ •๋‹ต์ด๋‹ค.