데이터사이언스 기록기📚

[백준/Python] 7562번(그래프, BFS)_나이트의 이동 본문

Coding Test/백준(Python)

[백준/Python] 7562번(그래프, BFS)_나이트의 이동

syunze 2023. 5. 8. 19:06

📌문제 유형

그래프 이론, 그래프 탐색, BFS(실버1)

 

📌문제

 

7562번: 나이트의 이동

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

www.acmicpc.net

 

📌나의 문제풀이

from collections import deque

t = int(input())

for _ in range(t):
    l = int(input())
    maps = [[0 for _ in range(l)] for _ in range(l)]
    s_x, s_y = map(int,input().split())
    e_x, e_y = map(int,input().split())

    q = deque()
    q.append([s_x, s_y])
    maps[s_x][s_y] = 1
    cnt = 0

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

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

        for i in range(8):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < l and 0 <= ny < l:
                if maps[nx][ny] == 0:
                    q.append([nx,ny])
                    maps[nx][ny] = maps[x][y] + 1
    print(maps[e_x][e_y] - 1)

 

📌 다른사람의 문제풀이

from collections import deque
import sys
input = sys.stdin.readline

t = int(input().rstrip())


def bfs() :
    dx = [-1, 1, 2, 2, 1, -1, -2, -2]
    dy = [2, 2, 1, -1, -2, -2, -1, 1]

    q = deque()
    q.append((startX, startY))
    while q :
        x, y = q.popleft()
        if x == endX and y == endY :
            return matrix[x][y] -1 
        for i in range(8) :
            nx = x + dx[i]
            ny = y + dy[i]
            if 0<=nx<l and 0<=ny<l and matrix[nx][ny] == 0 :
                matrix[nx][ny] = matrix[x][y] + 1
                q.append((nx,ny))
                
            
        
for _ in range(t) :
    l = int(input().rstrip())
    startX, startY = map(int, input().rstrip().split())
    endX, endY = map(int, input().rstrip().split())
    matrix = [[0]*l for _ in range(l)]
    matrix[startX][startY] = 1
    print(bfs())

 

📌 리뷰 

- BFS는 '현재 그래프 값 + 1'로 만들어서 탐색하는 경우가 많다는 것을 잊지말기!

- maps[nx][ny] + 1을 답지 설명보고 깨달음...!

728x90
Comments