ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

14442๋ฒˆ: ๋ฒฝ ๋ถ€์ˆ˜๊ณ  ์ด๋™ํ•˜๊ธฐ 2

์ฒซ์งธ ์ค„์— N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 1,000), K(1 ≤ K ≤ 10)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์— M๊ฐœ์˜ ์ˆซ์ž๋กœ ๋งต์ด ์ฃผ์–ด์ง„๋‹ค. (1, 1)๊ณผ (N, M)์€ ํ•ญ์ƒ 0์ด๋ผ๊ณ  ๊ฐ€์ •ํ•˜์ž.

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์•ž์„œ ๋‹ค๋ฃฌ ๋ฒฝ ๋ถ€์ˆ˜๊ณ  ์ด๋™ํ•˜๊ธฐ ๋ฌธ์ œ์—์„œ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ K๋กœ ์ถ”๊ฐ€๋œ ๋ฌธ์ œ์ด๋‹ค. ํ•ด๋‹น ๋ฌธ์ œ์—์„œ๋Š” ์ž…๋ ฅ๋˜๋Š” K์— ๋”ฐ๋ผ ๋ฒฝ์„ ๋ถ€ ์ˆ  ์ˆ˜ ์žˆ๋Š” ํšŸ์ˆ˜๊ฐ€ ์ฆ๊ฐ€ํ•˜๊ฒŒ ๋œ๋‹ค. ๋”ฐ๋ผ์„œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋Š” ๋ฒฝ์„ ๋ถ€์ˆœ ํšŸ์ˆ˜๊ฐ€ (0, 1, ... K)๋กœ ์ฆ๊ฐ€๋œ ๋ฌธ์ œ์ด๋‹ค. ๋ฒฝ ๋ถ€์ˆ˜๊ณ  ์ด๋™ํ•˜๊ธฐ ์ฝ”๋“œ์—์„œ K์— ๋Œ€ํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ๋ฉด ํ•ด๊ฒฐ ํ•  ์ˆ˜ ์žˆ๋‹ค. (๋‹จ, PyPy3๋กœ ์ œ์ถœํ•˜์—ฌ์•ผ ์‹œ๊ฐ„ ๋‚ด์— ํ†ต๊ณผํ•  ์ˆ˜ ์žˆ๋‹ค.)

 

์ฝ”๋“œ

from sys import stdin
from collections import deque


def visitable(x, y, w):
    return 0 <= x < n and 0 <= y < m and not visited[x][y][w]


def bfs(start):
    q = deque([start])
    dirs = ((-1, 0), (0, 1), (1, 0), (0, -1))

    while q:
        cur_x, cur_y, wall = q.popleft()
        dist = visited[cur_x][cur_y][wall] + 1

        if [cur_x, cur_y] == [n - 1, m - 1]:
            return visited[cur_x][cur_y][wall]

        for x, y in dirs:
            next_x, next_y = cur_x + x, cur_y + y
            if visitable(next_x, next_y, wall):
                if not graph[next_x][next_y]:
                    visited[next_x][next_y][wall] = dist
                    q.append((next_x, next_y, wall))
                elif wall < k:
                    visited[next_x][next_y][wall + 1] = dist
                    q.append((next_x, next_y, wall + 1))

    return -1


if __name__ == '__main__':
    n, m, k = map(int, stdin.readline().split())
    graph = [list(map(int, stdin.readline().strip())) for _ in range(n)]
    visited = [[[0] * (k + 1) for _ in range(m)] for _ in range(n)]
    visited[0][0] = [1] * (k + 1)
    print(bfs((0, 0, 0)))
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€