πŸ—οΈ Algorithm/🟩 λ°±μ€€

🟩 [λ°±μ€€] [Python] [BFS/DFS] 7562번_λ‚˜μ΄νŠΈμ˜ 이동

Dbswnstjd 2022. 11. 16. 20:03

문제

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

 

7562번: λ‚˜μ΄νŠΈμ˜ 이동

체슀판 μœ„μ— ν•œ λ‚˜μ΄νŠΈκ°€ 놓여져 μžˆλ‹€. λ‚˜μ΄νŠΈκ°€ ν•œ λ²ˆμ— 이동할 수 μžˆλŠ” 칸은 μ•„λž˜ 그림에 λ‚˜μ™€μžˆλ‹€. λ‚˜μ΄νŠΈκ°€ μ΄λ™ν•˜λ €κ³  ν•˜λŠ” 칸이 주어진닀. λ‚˜μ΄νŠΈλŠ” λͺ‡ 번 움직이면 이 칸으둜 이동할 수

www.acmicpc.net

풀이

λ¨Όμ € BFS둜 ν’€μ—ˆμ„ λ•Œ μ‹œκ°„μ΄ˆκ³Όκ°€ λ‚˜μ„œ pypy3둜 ν™•μΈν•΄λ΄€λ”λ‹ˆ μ„±κ³΅ν•˜μ˜€λ‹€. 

μ™œ μ‹œκ°„μ΄ˆκ³Όκ°€ λ‚¬λŠ”μ§€ 곰곰히 μƒκ°ν•΄λ³΄λ©΄μ„œ μ‹œκ°„λ³΅μž‘λ„λ₯Ό 계산해보고 연산을 μ΅œμ†Œν™” μ‹œν‚€λ„λ‘ μ½”λ“œλ₯Ό λ°”κΎΈμ—ˆλ‹€.

# λ°±μ€€ 7562번 문제 - λ‚˜μ΄νŠΈμ˜ 이동
from collections import deque
import sys
input = sys.stdin.readline
dx = [1,1,-1,-1,2,2,-2,-2]
dy = [2,-2,2,-2,1,-1,1,-1]
t = int(input())
def bfs(cur_x, cur_y):
    queue = deque()
    queue.append((cur_x, cur_y))
    while queue:
        x, y = queue.popleft()
        if x == move_x and y == move_y:
            print(graph[x][y])
            break
        for i in range(8):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0 <= nx < l and 0 <= ny < l and graph[nx][ny] == 0:
                graph[nx][ny] = graph[x][y] + 1
                queue.append((nx, ny))
for _ in range(t):
    l = int(input())
    graph = [[0]*(l) for _ in range(l)]
    cur_x, cur_y = map(int, input().split())
    move_x, move_y = map(int, input().split())
    bfs(cur_x, cur_y)

 

 

λ‚˜μ˜ 처음 풀이

# λ°±μ€€ 7562번 문제 - λ‚˜μ΄νŠΈμ˜ 이동
from collections import deque
import sys
dx = [1,1,-1,-1,2,2,-2,-2]
dy = [2,-2,2,-2,1,-1,1,-1]
t = int(input())
def bfs(cur_x, cur_y):
    queue = deque()
    queue.append((cur_x, cur_y))
    while queue:
        x, y = queue.popleft()
        
        for i in range(8):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or nx >= l or ny < 0 or ny >= l:
                continue
            if graph[nx][ny] == 0:
                graph[nx][ny] = 1
                visited[nx][ny] = visited[x][y] + 1
                queue.append((nx, ny))
            if graph[nx][ny] == 2:
                graph[nx][ny] = 1
                visited[nx][ny] = visited[x][y] + 1
for _ in range(t):
    l = int(input())
    graph = [[0]*(l) for _ in range(l)]
    visited = [[0]*(l) for _ in range(l)]
    cur_x, cur_y = map(int, input().split())
    move_x, move_y = map(int, input().split())

    graph[move_x][move_y] = 2
    if cur_x == move_x and cur_y == move_y:
        print(0)
    else:
        bfs(cur_x, cur_y)
        print(visited[move_x][move_y])