ν‹°μŠ€ν† λ¦¬ λ·°

728x90
λ°˜μ‘ν˜•

문제

 

16948번: 데슀 λ‚˜μ΄νŠΈ

κ²Œμž„μ„ μ’‹μ•„ν•˜λŠ” νλΈŒλŸ¬λ²„λŠ” μ²΄μŠ€μ—μ„œ μ‚¬μš©ν•  μƒˆλ‘œμš΄ 말 "데슀 λ‚˜μ΄νŠΈ"λ₯Ό λ§Œλ“€μ—ˆλ‹€. 데슀 λ‚˜μ΄νŠΈκ°€ μžˆλŠ” 곳이 (r, c)라면, (r-2, c-1), (r-2, c+1), (r, c-2), (r, c+2), (r+2, c-1), (r+2, c+1)둜 이동할 수 μžˆλ‹€. 크

www.acmicpc.net

 

문제 풀이

N * N 체슀판 내에 데슀 λ‚˜μ΄νŠΈκ°€ r1, c1에 μžˆμ„ λ•Œ, r2, c2에 λ°©λ¬Έκ°€λŠ₯ ν•œμ§€λ₯Ό νŒλ‹¨ν•˜λŠ” λ¬Έμ œμ΄λ‹€. 데슀 λ‚˜μ΄νŠΈλŠ” λ¬Έμ œμ— 주어진 것과 같이 6가지 λ°©ν–₯으둜 움직일 수 μžˆλ‹€. λ”°λΌμ„œ ν•œ μ •μ μœΌλ‘œ λΆ€ν„° λ°©λ¬Έν•  수 μžˆλŠ” λͺ¨λ“  경우의 μˆ˜λŠ” μ‹œλ„ 횟수 1둜 μƒκ°ν•˜μ—¬μ•Ό ν•œλ‹€. 데슀 λ‚˜μ΄νŠΈκ°€ λ°©λ¬Έν•  수 μžˆλŠ” λͺ¨λ“  정점을 λ‹€ λ°©λ¬Έν•˜μ—¬λ„, r2, c2에 λ„λ‹¬ν•˜μ§€ λͺ»ν•œ κ²½μš°λŠ” 닡을 찾을 수 μ—†λŠ” κ²½μš°λ‹€.

 

μ½”λ“œ

from sys import stdin
from collections import deque


def visitable(x, y, visited):
    return 0 <= x < n and 0 <= y < n and not visited[x][y]


def bfs(start):
    q = deque([start])
    visited = [[False] * n for _ in range(n)]
    answer = 0
    dirs = ((-2, -1), (-2, 1), (0, -2), (0, 2), (2, -1), (2, 1))

    while q:
        answer += 1

        for _ in range(len(q)):
            cur_x, cur_y = q.popleft()
            for x, y in dirs:
                next_x, next_y = cur_x + x, cur_y + y
                if [next_x, next_y] == end:
                    return answer

                if visitable(next_x, next_y, visited):
                    visited[next_x][next_y] = True
                    q.append([next_x, next_y])
    return -1


if __name__ == '__main__':
    n = int(stdin.readline())
    locations = list(map(int, stdin.readline().split()))
    start, end = locations[:2], locations[2:]
    print(bfs(start))

 

728x90
λ°˜μ‘ν˜•
λŒ“κΈ€
κΈ€ 보관함
μ΅œκ·Όμ— 올라온 κΈ€
μ΅œκ·Όμ— 달린 λŒ“κΈ€