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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

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

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

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ์•ž์„œ ๋‹ค๋ฃฌ ๋ฌธ์ œ์ธ ๋ฒฝ ๋ถ€์ˆ˜๊ณ  ์ด๋™ํ•˜๊ธฐ 2 ๋ฌธ์ œ์—์„œ ๋‚ฎ์—๋งŒ ๋ฒฝ์„ ๋ถ€์ˆ  ์ˆ˜ ์žˆ๊ณ , ๋ฐค์—๋Š” ๋ฒฝ์„ ๋ถ€์ˆ  ์ˆ˜ ์—†๋‹ค๋Š” ์กฐ๊ฑด์ด ์ถ”๊ฐ€๋œ ๋ฌธ์ œ์ด๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” ํ† ๋งˆํ†  ๋ฌธ์ œ์™€ ๊ฐ™์ด ํ•˜๋ฃจ์— ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฒ˜๋ฆฌํ•˜์—ฌ์•ผ ํ•˜๋ฏ€๋กœ, day 2 ์ถ”๊ฐ€๋œ ๊ฒฝ์šฐ์˜ ์ˆ˜๊ฐ€ 3์ด๋ผ๋ฉด ํ•˜๋ฃจ ๋™์•ˆ ์ฒ˜๋ฆฌ ๋˜๋„๋ก ํ•˜์—ฌ์•ผ ํ•œ๋‹ค. ์ด๋Š” ํ์˜ ๊ธธ์ด๋งŒํผ ์ฒ˜๋ฆฌํ•˜๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

 

์ฝ”๋“œ

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))
    day = 1

    while q:
        night = False if day > 0 else True

        for _ in range(len(q)):
            cur_x, cur_y, wall = q.popleft()
            today = abs(day)

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

            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] = today + 1
                        q.append((next_x, next_y, wall))
                    elif wall < k and not visited[next_x][next_y][wall + 1]:
                        if not night:
                            visited[next_x][next_y][wall + 1] = today + 1
                            q.append((next_x, next_y, wall + 1))
                        else:
                            q.append((cur_x, cur_y, wall))

        day = day + 1 if day > 0 else day - 1
        day *= -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)))

 ๋‚ฎ๊ณผ ๋ฐค์€ ํ˜„์žฌ ๋‚ ์งœ๊ฐ€ ์–‘์ˆ˜์ด๋ฉด ๋‚ฎ, ์Œ์ˆ˜์ด๋ฉด ๋ฐค์œผ๋กœ ๊ตฌ๋ถ„ํ•˜๋„๋ก ํ•˜์˜€๋‹ค. ์ด ๋ฌธ์ œ ์—ญ์‹œ ํŒŒ์ด์ฌ์œผ๋กœ๋Š” ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•˜๋ฉฐ PyPy3๋กœ ์ œ์ถœํ•˜์—ฌ์•ผ ํ•œ๋‹ค. 17%์—์„œ ๊ณ„์† ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ๋‚˜์„œ ํ™•์ธํ•ด ๋ณด๋‹ˆ, ๋ฒฝ์ธ ๊ฒฝ์šฐ์— ์žฌ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ์ฒดํฌํ•˜์ง€ ์•Š์•„ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋‹ค.

์ตœ์ดˆ์— ์ž‘์„ฑํ•œ ์ฝ”๋“œ์˜ ๊ฒฐ๊ณผ

 

์œ„์˜ ์ฝ”๋“œ๋กœ ์‹คํ–‰ํ•œ ๊ฒฐ๊ณผ

 ์ตœ๋Œ€ํ•œ ์กฐ๊ฑด ํŒ๋‹จ์„ ์ค„์ด๊ณ , ์ด๋ฆฌ์ €๋ฆฌ ์ˆ˜์ •ํ•œ ๊ฒฐ๊ณผ ์ดˆ๊ธฐ์— ์ž‘์„ฑํ•˜์˜€์„ ๋•Œ ๋ณด๋‹ค, ์‹œ๊ฐ„๊ณผ ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰์„ ์ค„์ผ ์ˆ˜ ์žˆ์—ˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€