๐Ÿค–/๋ฐฑ์ค€

๋ฐฑ์ค€ 2178: ๋ฏธ๋กœ ํƒ์ƒ‰ (Python)

sssbin 2022. 2. 1. 17:12

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

 

2178๋ฒˆ: ๋ฏธ๋กœ ํƒ์ƒ‰

์ฒซ์งธ ์ค„์— ๋‘ ์ •์ˆ˜ N, M(2 ≤ N, M ≤ 100)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” M๊ฐœ์˜ ์ •์ˆ˜๋กœ ๋ฏธ๋กœ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ๊ฐ์˜ ์ˆ˜๋“ค์€ ๋ถ™์–ด์„œ ์ž…๋ ฅ์œผ๋กœ ์ฃผ์–ด์ง„๋‹ค.

www.acmicpc.net

 

์ด์ฝ”ํ…Œ ๊ต์žฌ์— ์žˆ๋˜ ๋ฌธ์ œ์ด๊ธฐ๋„ ํ•˜๊ณ  ์–ด๋Š ์ •๋„ ๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ ๋ฌธ์ œ์— ์ต์ˆ™ํ•ด์ ธ์„œ ๋น ๋ฅด๊ฒŒ ํ’€์—ˆ๋‹ค

์—ญ์‹œ ์‚ฌ๋žŒ์€ ๋ณต์Šต์ด ์ค‘์š”ํ•˜๊ณ  ๊พธ์ค€ํžˆ ๊ณต๋ถ€ํ•ด์•ผ ํ•œ๋‹ค,,,

์ด ๋ฌธ์ œ ์ฒ˜์Œ ํ’€์—ˆ์„ ๋• ๋‹ต์ด ๋„๋ฌด์ง€ ์•ˆ ๋‚˜์™”๋Š”๋ฐ ๋‹ค์‹œ ํ‘ธ๋‹ˆ๊นŒ ์‰ฝ๊ฒŒ ํ’€๋ฆผ

 

from collections import deque

n, m = map(int, input().split())
miro = [[] for _ in range(n)]

for i in range(n):
    data = input()
    for j in range(m):
        miro[i].append(int(data[j]))


def bfs(x, y):
    queue = deque()
    queue.append([x, y])

    dx = [1, -1, 0, 0]
    dy = [0, 0, 1, -1]

    while queue:
        qx, qy = queue.popleft()

        for i in range(4):
            mx = qx + dx[i]
            my = qy + dy[i]

            if mx < 0 or mx >= n or my < 0 or my >= m:
                continue

            if miro[mx][my] == 1:
                miro[mx][my] = miro[qx][qy] + 1
                queue.append([mx, my])

    return miro[n-1][m-1]

print(bfs(0,0))

 

๋‚˜๋ž‘ ๊ฐ€๊นŒ์šด ๊ณณ๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•ด์•ผ ํ•˜๋‹ˆ๊นŒ bfs๋กœ ํ’€์—ˆ๋‹ค

์—ญ์‹œ๋‚˜ ์ด๋™๋ฐฐ์—ด ๋งŒ๋“ค์–ด์„œ ์ƒํ•˜์ขŒ์šฐ ํƒ์ƒ‰ํ•ด์ฃผ๊ณ  ๊ธธ์ด ์žˆ๋Š” ๊ณณ์œผ๋กœ ๊ฐ€๋ฉด ์›๋ž˜ ์ขŒํ‘œ์˜ ๊ฐ’ + 1

์–ด์ฐจํ”ผ ๋ฏธ๋กœ๋Š” ํ•œ ๊ธธ๋กœ ๋‹ค ์ด์–ด์ ธ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๋งจ ์ฒ˜์Œ ์ขŒํ‘œ๋กœ bfs ๋Œ๋ฆฌ๊ณ  ๋งจ ๋งˆ์ง€๋ง‰ ์ขŒํ‘œ์— ์ €์žฅ๋œ ๊ฐ’์„ ์ถœ๋ ฅํ•ด์ฃผ๋ฉด ๋œ๋‹ค!