Post

๐Ÿน ์žฅ๊ตฐ

1. ๋ฌธ์ œ ๋งํฌ

16509๋ฒˆ: ์žฅ๊ตฐ


2. ์ฝ”๋“œ

Python3 34104KB 88ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# ์ƒ ์œ„์น˜
sx, sy = map(int, input().split())
# ์™• ์œ„์น˜
kx, ky = list(map(int, input().split()))

# ์ƒ์ขŒ, ์ƒ์šฐ, ํ•˜์ขŒ, ํ•˜์šฐ, ์ขŒ์ƒ, ์ขŒํ•˜, ์šฐ์ƒ, ์šฐํ•˜
dx = [[-1, -1, -1], [-1, -1, -1], [1, 1, 1], [1, 1, 1], [0, -1, -1], [0, 1, 1], [0, -1, -1], [0, 1, 1]]
dy = [[0, -1, -1], [0, 1, 1], [0, -1, -1], [0, 1, 1], [-1, -1, -1], [-1, -1, -1], [1, 1, 1], [1, 1, 1]]

dist = [[0] * 9 for _ in range(10)]

from collections import deque

def bfs():
    q = deque([])
    q.append((sx, sy))
    while q:
        x, y = q.popleft()
        # ์™•์— ๋„๋‹ฌ
        if x == kx and y == ky:
            return dist[x][y]
        for i in range(8):
            flag = True
            nx, ny = x, y
            for j in range(3):
                nx += dx[i][j]
                ny += dy[i][j]
                # ์žฅ๊ธฐํŒ ๋ฐ–์œผ๋กœ ์ด๋™ํ•  ๋•Œ
                if nx < 0 or nx >= 10 or ny < 0 or ny >= 9:
                    flag = False
                    break
                # ์ด๋™ ๊ฒฝ๋กœ์— ๋‹ค๋ฅธ ๊ธฐ๋ฌผ(์™•)์ด ์žˆ์„ ์‹œ
                if j != 2 and nx == kx and ny == ky:
                    flag = False
                    break
            # ์ด๋™ ๊ฐ€๋Šฅํ•œ ์นธ์ด๊ณ  ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋‹ค๋ฉด
            if flag == True and dist[nx][ny] == 0:
                dist[nx][ny] = dist[x][y] + 1   # ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ํ‘œ์‹œ 
                q.append((nx, ny))
        
    # ์™•์—๊ฒŒ ๋„๋‹ฌ ๋ถˆ๊ฐ€ ์‹œ
    return -1

print(bfs())


3. ํ•ด์„ค

์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๊ธฐ ์œ„ํ•ด bfs(๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰)์„ ์‚ฌ์šฉํ•ด์ฃผ์—ˆ๋‹ค.

๊ฐ ์œ„์น˜์˜ ์ตœ๋‹จ ๊ฒฝ๋กœ ์ •๋ณด๋ฅผ dist 2์ฐจ์› ๋ฐฐ์—ด์— ๋„ฃ์–ด์ค€๋‹ค.

์ƒ์ด ์›€์ง์ผ ์ˆ˜ ์žˆ๋Š” ์ด 8๊ฐ€์ง€์˜ ๊ฒฝ์šฐ์—์„œ ์ด๋™ ๊ฐ€๋Šฅ ์œ„์น˜ 3๊ฐ€์ง€๋ฅผ 2์ค‘ ํฌ๋ฌธ์œผ๋กœ ํ™•์ธํ•ด์ค€๋‹ค.

๊ฐ ์œ„์น˜๊ฐ€ ์žฅ๊ธฐํŒ ๋‚ด์— ์žˆ๊ณ , ์ด๋™ ๊ฒฝ๋กœ์— ๋‹ค๋ฅธ ๊ธฐ๋ฌผ(์™•)์ด ์—†๋Š”์ง€ ํ™•์ธํ•ด์ฃผ๊ณ  ์กฐ๊ฑด์„ ๋งŒ์กฑํ–ˆ์„ ๋•Œ ์ด๋™ํ•œ ์นธ์˜ ์œ„์น˜๊ฐ€ ์ฒ˜์Œ ๋„์ฐฉํ•œ ์œ„์น˜๋ผ๋ฉด(dist์˜ ๊ฐ’์ด 0) ํ•ด๋‹น ์œ„์น˜์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ๊ฐ’์„ ๋„ฃ์–ด์ค€๋‹ค.

์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋Š” โ€˜์ด๋™ ๋ฐ”๋กœ ์ง์ „ ์นธ ๊ฑฐ๋ฆฌ + 1โ€™์ด๋‹ค.

ํ˜„์žฌ ์ƒ์˜ ์œ„์น˜๊ฐ€ ์™•์˜ ์œ„์น˜๊ฐ€ ๊ฐ™๋‹ค๋ฉด ํ•ด๋‹น ์œ„์น˜์˜ dist๊ฐ’์„ ๋ฆฌํ„ดํ•œ๋‹ค.

๋งŒ์•ฝ ํ๋ฅผ ๋ชจ๋‘ ๋Œ์•˜์„ ๋•Œ๋„ ์™•์„ ๋งŒ๋‚˜์ง€ ๋ชปํ•œ๋‹ค๋ฉด -1์„ ๋ฆฌํ„ดํ•œ๋‹ค.

This post is licensed under CC BY 4.0 by the author.