๐Ÿค–/๋ฐฑ์ค€

๋ฐฑ์ค€ 7564: ๋‚˜์ดํŠธ์˜ ์ด๋™ (Python)

sssbin 2022. 2. 3. 19:58

 

https://www.acmicpc.net/problem/7562

 

7562๋ฒˆ: ๋‚˜์ดํŠธ์˜ ์ด๋™

์ฒด์ŠคํŒ ์œ„์— ํ•œ ๋‚˜์ดํŠธ๊ฐ€ ๋†“์—ฌ์ ธ ์žˆ๋‹ค. ๋‚˜์ดํŠธ๊ฐ€ ํ•œ ๋ฒˆ์— ์ด๋™ํ•  ์ˆ˜ ์žˆ๋Š” ์นธ์€ ์•„๋ž˜ ๊ทธ๋ฆผ์— ๋‚˜์™€์žˆ๋‹ค. ๋‚˜์ดํŠธ๊ฐ€ ์ด๋™ํ•˜๋ ค๊ณ  ํ•˜๋Š” ์นธ์ด ์ฃผ์–ด์ง„๋‹ค. ๋‚˜์ดํŠธ๋Š” ๋ช‡ ๋ฒˆ ์›€์ง์ด๋ฉด ์ด ์นธ์œผ๋กœ ์ด๋™ํ•  ์ˆ˜

www.acmicpc.net

 

from collections import deque

t = int(input())

def bfs(x1, y1, x2, y2):
    queue = deque()
    queue.append([x1, y1])

    chess[x1][y1] = 1

    dx = [-1, -2, -2, -1, 1, 2, 2, 1]
    dy = [-2, -1, 1, 2, 2, 1, -1, -2]

    while queue:
        qx, qy = queue.popleft()

        if qx == x2 and qy == y2:
            print(chess[qx][qy] - 1)
            break

        for i in range(8):
            x = qx + dx[i]
            y = qy + dy[i]

            if x < 0 or x >= n or y < 0 or y >= n:
                continue

            if chess[x][y] == 0:
                queue.append([x, y])
                chess[x][y] = chess[qx][qy] + 1


for i in range(t):
    n = int(input())
    chess = [[0 for _ in range(n)] for _ in range(n)]
    start = list(map(int, input().split()))
    end = list(map(int, input().split()))
    bfs(start[0], start[1], end[0], end[1])

 

๋ฏธ๋กœ ํƒ์ƒ‰ ๋ฌธ์ œ๋ž‘ ๊ฑฐ์˜ ๋˜‘๊ฐ™๋‹ค

์ขŒํ‘œ ์ด๋™ ๋ฐฐ์—ด๋งŒ ์ƒํ•˜์ขŒ์šฐ๊ฐ€ ์•„๋‹Œ ๊ทธ๋ฆผ์— ๋‚˜์™€์žˆ๋Š” ์ขŒํ‘œ๋กœ ํ•ด์ฃผ๋ฉด ๋œ๋‹ค!

๋œ ๊ฑฐ ๊ฐ™์€๋ฐ ๊ณ„์† ๋‹ต์ด ์•ˆ ๋‚˜์™€์„œ ํ—ค๋งค๊ณ  ์žˆ์—ˆ๋Š”๋ฐ

ํ๋ฅผ ํ•จ์ˆ˜ ๋ฐ”๊นฅ์— ์„ ์–ธํ•ด์„œ ํ์— ์ „์— ์ผ๋˜ ์ขŒํ‘œ๋“ค์ด ๋‚จ์•„์žˆ์–ด์„œ ๊ทธ๋Ÿฐ๊ฑฐ์˜€๋‹ค,,,