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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

6087๋ฒˆ: ๋ ˆ์ด์ € ํ†ต์‹ 

ํฌ๊ธฐ๊ฐ€ 1×1์ธ ์ •์‚ฌ๊ฐํ˜•์œผ๋กœ ๋‚˜๋ˆ„์–ด์ง„ W×H ํฌ๊ธฐ์˜ ์ง€๋„๊ฐ€ ์žˆ๋‹ค. ์ง€๋„์˜ ๊ฐ ์นธ์€ ๋นˆ ์นธ์ด๊ฑฐ๋‚˜ ๋ฒฝ์ด๋ฉฐ, ๋‘ ์นธ์€ 'C'๋กœ ํ‘œ์‹œ๋˜์–ด ์žˆ๋Š” ์นธ์ด๋‹ค. 'C'๋กœ ํ‘œ์‹œ๋˜์–ด ์žˆ๋Š” ๋‘ ์นธ์„ ๋ ˆ์ด์ €๋กœ ํ†ต์‹ ํ•˜๊ธฐ ์œ„ํ•ด์„œ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ๋ ˆ์ด์ €์™€ ๋ ˆ์ด์ € ์‚ฌ์ด์˜ ํ†ต์‹ ์„ ํ•˜๊ธฐ ์œ„ํ•ด ์ตœ์†Œํ•œ์˜ ๊ฑฐ์šธ์„ ์„ค์น˜ํ•˜์—ฌ ํ†ต์‹ ์ด ๊ฐ€๋Šฅํ•˜๋„๋ก ํ•˜๋Š” ๊ฑฐ์šธ์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋ ˆ์ด์ €๊ฐ€ ๋ฐฉํ–ฅ์„ ๋ฐ”๊พธ์ง€ ์•Š๊ณ  ์ตœ๋Œ€ํ•œ ๋‚˜์•„๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์™€, ๋ฐฉํ–ฅ์„ ๋ฐ”๊พธ๋Š” ๊ฒฝ์šฐ๋ฅผ ์ƒ๊ฐํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ์ ‘๊ทผํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋กœ์ง์„ ์ƒ๊ฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

  • BFS๋กœ ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•œ๋‹ค.
  • ๋ฐฉํ–ฅ์„ ๋ฐ”๊พธ์ง€ ์•Š๊ณ  ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ๋กœ๋“ค์„ ์ตœ๋Œ€ํ•œ ํƒ์ƒ‰ํ•œ๋‹ค.
    • ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜์ง€ ์•Š๊ฑฐ๋‚˜, ๋ฒฝ์ด ์•„๋‹Œ ๊ฒฝ์šฐ๋ฅผ ๋งํ•œ๋‹ค.
  • ๋ฐฉํ–ฅ์ด ๋ฐ”๋€Œ๊ฒŒ ๋œ๋‹ค๋ฉด ๊ธฐ์กด์— ๋ฐฉํ–ฅ์„ ๋ฐ”๊พธ์ง€ ์•Š๊ณ  ์ตœ๋Œ€ํ•œ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์—์„œ +1 ํ•œ๋‹ค.
    • ์ฆ‰, ๋ฐฉํ–ฅ์ด ๋ณ€๊ฒฝ๋˜์–ด `๊ฑฐ์šธ ํ•˜๋‚˜๋ฅผ ์„ค์น˜`ํ•˜๊ฒŒ ๋œ๋‹ค.
  • ๋‹ค๋ฅธ ๋ ˆ์ด์ €์— ๋„๋‹ฌํ•  ๋•Œ ๊ฐ€์ง€, ์œ„์˜ ๋กœ์ง์„ ๋ฐ˜๋ณตํ•˜๋ฉด `์ตœ์†Œ ๊ฑฐ์šธ์˜ ๊ฐœ์ˆ˜`๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin
from collections import deque
from math import inf


def visitable(x, y):
    return 0 <= x < h and 0 <= y < w


def bfs():
    q = deque([start])
    visited[start[X]][start[Y]] = 0

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

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

            while visitable(next_x, next_y) and graph[next_x][next_y] != '*':
                if visited[next_x][next_y] < visited[x][y] + 1:
                    break

                q.append((next_x, next_y))
                visited[next_x][next_y] = visited[x][y] + 1

                next_x += dx
                next_y += dy

    return visited[end[X]][end[Y]] - 1


if __name__ == "__main__":
    X, Y = 0, 1
    dirs = ((0, 1), (0, -1), (1, 0), (-1, 0))
    w, h = map(int, stdin.readline().split())
    graph = [list(stdin.readline().rstrip()) for _ in range(h)]
    visited = [[inf] * w for _ in range(h)]
    laser = []

    for i in range(h):
        for j in range(w):
            if graph[i][j] == 'C':
                laser.append([i, j])

    start, end = laser
    print(bfs())

 

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