백준

백준 7562 나이트의 이동(Java)

Park DJ 2023. 2. 16. 22:26

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

 

7562번: 나이트의 이동

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

www.acmicpc.net


 

 

Java 코드

 


import java.util.Scanner;
import java.util.Queue;
import java.util.LinkedList;

public class Main {

  static int l;
  static int[][] arr;
  static int[] dx = {2, 1, -1, -2, -2, -1, 1, 2};
  static int[] dy = {1, 2, 2, 1, -1, -2, -2, -1};
  static StringBuilder sb = new StringBuilder();
  
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    
    int t = sc.nextInt();
    
    for(int i = 0; i < t; i++) {
      l = sc.nextInt();
      arr = new int[l][l];
      int x1 = sc.nextInt();
      int y1 = sc.nextInt();
      int x2 = sc.nextInt();
      int y2 = sc.nextInt();
      bfs(x1, y1, x2, y2);
    }


    System.out.println(sb);
  }

  public static void bfs(int x1, int y1, int x2, int y2) {
    Queue<int[]> q = new LinkedList<>();
    arr[x1][y1] = 1;
    q.add(new int[] {x1, y1});
    while(!q.isEmpty()) {
      int[] num = q.poll();
      if(num[0] == x2 && num[1] == y2) {
        sb.append(arr[x2][y2] - 1).append("\n");
        return;
      }
      for(int i = 0; i < 8; i++) {
        int x = num[0] + dx[i];
        int y = num[1] + dy[i];
        if(x >= 0 && x < l && y >= 0 && y < l && arr[x][y] == 0) {
          arr[x][y] = arr[num[0]][num[1]] + 1;
          q.add(new int[] {x, y});
        }
      }
    }
  }
  
}