Algorithm Problem/Python

[python] ๋ฐฑ์ค€ - 7562. ๋‚˜์ดํŠธ์˜ ์ด๋™

deo2kim 2020. 10. 2. 08:00
๋ฐ˜์‘ํ˜•

๐Ÿค”๋ฌธ์ œ ํ•ด๊ฒฐ

  • S2 | BFS

BFS๋กœ ๋‹ค ๋Œ์•„์ฃผ๋‹ค๊ฐ€ ๋„์ฐฉ์ง€๋ฅผ ๋งŒ๋‚˜๋ฉด ๋!

 

๐Ÿ’ป์†Œ์Šค ์ฝ”๋“œ

from collections import deque


def bfs():
    q = deque()
    q.append((start_x, start_y))
    while q:
        cx, cy = q.popleft()
        if cx == end_x and cy == end_y:
            print(chess[cx][cy])
            return
        for k in range(len(dx)):
            nx = cx + dx[k]
            ny = cy + dy[k]
            if 0 <= nx < N and 0 <= ny < N and chess[nx][ny] == '':
                chess[nx][ny] = chess[cx][cy] + 1
                if nx == end_x and ny == end_y:
                    print(chess[nx][ny])
                    return

                q.append((nx, ny))


for tc in range(int(input())):
    N = int(input())
    chess = [[''] * N for _ in range(N)]
    start_x, start_y = map(int, input().split())
    end_x, end_y = map(int, input().split())
    chess[start_x][start_y] = 0
    dx, dy = [-2, -1, 1, 2, 2, 1, -1, -2], [1, 2, 2, 1, -1, -2, -2, -1]
    bfs()

 

๐Ÿ“•๋ฌธ์ œ ํ™•์ธ

์ถœ์ฒ˜: BACKJOON ONLINE JUDGE

๋งํฌ: https://www.acmicpc.net/problem/7562

 

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

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

www.acmicpc.net

๋ฐ˜์‘ํ˜•