아이공의 AI 공부 도전기

[Baekjoon] 7562번 : 나이트의 이동 (Python, 그래프, BFS)

 

     

 

 

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

 

7562번: 나이트의 이동

체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수

www.acmicpc.net

 

코드 링크

https://github.com/stellaluminary/Baekjoon

 

GitHub - stellaluminary/Baekjoon

Contribute to stellaluminary/Baekjoon development by creating an account on GitHub.

github.com

 

Python

 

방법 1 - 메모리 32468KB / 시간 2748ms / 코드 길이 805B

 

백트래킹 외 가장 쉬운 방법은 초기 진입한 최초 횟수를 기록하면서 진행하는 BFS이다.

고로 본 방법은 BFS로 문제를 푼다.

 

from collections import deque
dm = [(-2,-1),(-1,-2),(1,-2),(2,-1),(2,1),(1,2),(-1,2),(-2,1)]

def bfs(current, target, cnt, visit):
    q = deque([current])
    visit[current[0]][current[1]] = 1

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

        if [x,y] == target:
            return visit[x][y]

        for i in range(8):
            nx, ny = x+dm[i][0], y+dm[i][1]

            if nx < 0 or ny < 0 or nx >= l or ny >= l:
                continue
            if not visit[nx][ny]:
                visit[nx][ny] = visit[x][y] + 1
                q.append([nx, ny])

for _ in range(int(input())):
    l = int(input())
    present = list(map(int, input().split()))
    target = list(map(int, input().split()))

    visit = [[0]*l for _ in range(l)]
    val = bfs(present, target, 0, visit)
    print(val-1)

 

공유하기

facebook twitter kakaoTalk kakaostory naver band
loading