Post

[BOJ] 2178. ๋ฏธ๋กœํƒ์ƒ‰(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ๋งต ๋งŒ๋“ค๊ธฐ
    ์ขŒํ‘œ๊ฐ€ 1,1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•œ๋‹ค.์ธ๋ฑ์Šค์กฐ์ •์„ ํ•˜๋Š” ๋ฒˆ๊ฑฐ๋Ÿฌ์›€์„ ์ค„์—ฌ์•ผํ•˜๊ธฐ ๋•Œ๋ฌธ์— ํ–‰ 1์ค„๊ณผ ์—ด1์ค„์„ ๋ฏธ๋ฆฌ ๋„ฃ์–ด์ฃผ๊ณ  ์ž…๋ ฅ๊ฐ’์„ ๋„ฃ์–ด์ค€๋‹ค.

  2. (N,M)๊นŒ์ง€ ์ด๋™ํ•˜๊ธฐ
    ์ธ์ ‘ํ•œ ๊ณณ๋งŒ ์›€์ง์ผ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ์ƒํ•˜์ขŒ์šฐ๋กœ๋งŒ ์ด๋™์ด ๊ฐ€๋Šฅํ•˜๋‹ค.(dy,dx๋กœ ์„ค์ •) y,x์ขŒํ‘œ๊ฐ€ 1์ด์ƒ n, m์ดํ•˜์ผ๋•Œ ์ด๋™์ด ๊ฐ€๋Šฅํ•˜๊ณ  ๊ณผ๊ฑฐ์— ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ๊ณณ๋งŒ ์ด๋™ํ•˜๋„๋ก ํ•œ๋‹ค. (bfs์‚ฌ์šฉ)

  3. ๋„์ฐฉ์ง€๊นŒ์ง€ ์ง€๋‚˜๋Š” ์ตœ์†Œ์˜ ์นธ ์ˆ˜
    ์›€์ง์ผ ๋•Œ๋งˆ๋‹ค cnt๋ฅผ ์„ธ์„œ ๋ชฉํ‘œ์— ๋„์ฐฉํ•˜๋ฉด cnt๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋„๋ก ํ•˜์˜€๋‹ค. bfs๋Š” ์ตœ์†Œ ๊ฑฐ๋ฆฌ๋ฅผ ์ฐพ์„ ๋•Œ ์‚ฌ์šฉํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ œ์ผ ์ฒ˜์Œ ๋„์ฐฉ์ง€์— ๋„์ฐฉํ•  ๋–„๊ฐ€ ์ตœ์†Œ๊ฑฐ๋ฆฌ์ด๋‹ค.

๐Ÿฅ‚์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import sys
from collections import deque
input = sys.stdin.readline

def move(x,y):
    dy = (1,0,-1,0)
    dx = (0,1,0,-1)
    visited = [[False for _ in range(m+1)] for _ in range(n+1)]
    queue = deque()
    queue.append((y,x,1))
    visited[y][x] = True

    while queue:
        ny,nx,nxt_cnt = queue.popleft()
        if ny==n and nx==m: return nxt_cnt
        for i in range(4):
            ey = ny + dy[i]
            ex = nx + dx[i]
            if 1 <= ey <= n and 1 <= ex <= m:
                if board[ey][ex]==1 and not visited[ey][ex]:
                    visited[ey][ex]=True
                    queue.append((ey,ex,nxt_cnt+1))

n,m = map(int,input().split())
board=[]

board.append([0]*(m+1))
for _ in range(n):
    li=[0]
    tmp = input().rstrip()
    for i in tmp:
        li.append(int(i))
    board.append(li.copy())

print(move(1,1))
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.