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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

18405๋ฒˆ: ๊ฒฝ์Ÿ์  ์ „์—ผ

์ฒซ์งธ ์ค„์— ์ž์—ฐ์ˆ˜ N, K๊ฐ€ ๊ณต๋ฐฑ์„ ๊ธฐ์ค€์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 200, 1 ≤ K ≤ 1,000) ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ์„œ ์‹œํ—˜๊ด€์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ ํ–‰์€ N๊ฐœ์˜ ์›์†Œ๋กœ ๊ตฌ์„ฑ๋˜๋ฉฐ, ํ•ด๋‹น ์œ„์น˜๏ฟฝ๏ฟฝ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 NxN์— ์‹œํ—˜๊ด€์— ๋ฐ”์ด๋Ÿฌ์Šค๋“ค์ด ์žˆ์„ ๋•Œ, ๋ฐ”์ด๋Ÿฌ์Šค์˜ ์ข…๋ฅ˜๋Š” 1๋ถ€ํ„ฐ K๊นŒ์ง€ ์กด์žฌํ•œ๋‹ค. ์ด๋•Œ, 1๋ฒˆ ๋ฐ”์ด๋Ÿฌ์Šค๋ถ€ํ„ฐ ์šฐ์„ ์ ์œผ๋กœ ์ „์—ผ๋  ๋•Œ, S์ดˆ์— X, Y์— ์ „์—ผ๋œ ๋ฐ”์ด๋Ÿฌ์Šค์˜ ์ข…๋ฅ˜๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ์ดˆ๊ธฐ์— ์ „์—ผ๋˜์ง€ ์•Š์€ ๊ณณ์€ 0, ๋ฐ”์ด๋Ÿฌ์Šค๊ฐ€ ์žˆ๋Š” ๊ณณ์€ 1 ~ K ์‚ฌ์ด์˜ ์ˆ˜๋กœ ํ‘œ์‹œ๋œ๋‹ค.

 

  • BFS๋ฅผ ํ†ตํ•ด ํƒ์ƒ‰ํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ’€ ์ˆ˜ ์žˆ๋‹ค.
  • ์ตœ์ดˆ์— ์ฃผ์–ด์ง„ ์‹œํ—˜๊ด€์—์„œ ๋ฐ”์ด๋Ÿฌ์Šค์˜ ์ข…๋ฅ˜๋ฅผ ์ฐพ๊ณ , ์ขŒํ‘œ๋ฅผ ๊ธฐ๋กํ•œ๋‹ค.
    • 1๋ฒˆ ๋ฐ”์ด๋Ÿฌ์Šค ๋ถ€ํ„ฐ ์ „์—ผ๋˜์–ด์–ด์•ผ ํ•˜๋ฏ€๋กœ ์ฐพ์€ ๋ฐ”์ด๋Ÿฌ์Šค๋ฅผ ์ •๋ ฌํ•˜์—ฌ `deque`์— ์‚ฝ์ž…ํ•œ๋‹ค.
  • ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋กœ ํƒ์ƒ‰ํ•˜์—ฌ ์ „์—ผ์‹œํ‚จ๋‹ค.
  • ์ „์—ผ์„ ์ง„ํ–‰ํ•˜๋ฉฐ, ์‹œ๊ฐ„์ด S๊ฐ€ ๋˜๋Š” ๊ฒฝ์šฐ ์ „์—ผ์„ ์ค‘๋‹จ์‹œํ‚จ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from collections import deque


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


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

    while q:
        cur_virus, x, y, time = q.popleft()

        if time == target[S]:
            break

        for dx, dy in dirs:
            next_x, next_y = x + dx, y + dy

            if visitable(next_x, next_y):
                graph[next_x][next_y] = cur_virus
                q.append((cur_virus, next_x, next_y, time + 1))


if __name__ == '__main__':
    S, X, Y = 0, 1, 2
    n, k = map(int, stdin.readline().split())
    graph = [list(map(int, stdin.readline().split())) for _ in range(n)]
    target = list(map(int, stdin.readline().split()))
    virus = []

    for i in range(n):
        for j in range(n):
            if graph[i][j] != 0:
                virus.append([graph[i][j], i, j, 0])

    bfs(sorted(virus))

    print(graph[target[X] - 1][target[Y] - 1])
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€