ALGORITHM/프로그래머스 | 백준 | 삼성 | 카카오

[백준] 7562번 나이트의 이동

SZCODE 2020. 7. 28. 12:45

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

 

7562번: 나이트의 이동

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

www.acmicpc.net

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

public class Main {
	static int T, I, count;
	static int[][] map,
			dir = { { -2, -1 }, { -1, -2 }, { 1, 2 }, { 2, 1 }, { 1, -2 }, { -1, 2 }, { -2, 1 }, { 2, -1 } };
	static int[] current, next;
	static boolean[][] visited;
	static Queue<Pair> queue;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		T = sc.nextInt();
		for (int tc = 1; tc <= T; tc++) {
			I = sc.nextInt();
			map = new int[I][I];
			visited = new boolean[I][I];
			current = new int[2];
			next = new int[2];
			count = 0;
			queue = new LinkedList();

			current[0] = sc.nextInt();
			current[1] = sc.nextInt();
			next[0] = sc.nextInt();
			next[1] = sc.nextInt();

			if (current[0] == next[0] && current[1] == next[1]) {
				System.out.println(0);
			} else {
				queue.offer(new Pair(current[0], current[1]));
				bfs();
				System.out.println(count);
			}
		} // end of tc
	}

	public static void bfs() {
		visited[current[0]][current[1]] = true;

		while (!queue.isEmpty()) {

			int len = queue.size();
			count++;
			for (int l = 0; l < len; l++) {
				Pair p = queue.poll();

				for (int i = 0; i < dir.length; i++) {
					int nx = p.x + dir[i][0];
					int ny = p.y + dir[i][1];
					if (isInside(nx, ny) && !visited[nx][ny]) {
						if (nx == next[0] && ny == next[1]) {
							return;
						}

						queue.offer(new Pair(nx, ny));
						visited[nx][ny] = true;
					}
				}
			}
		}
	}

	public static boolean isInside(int x, int y) {
		return x >= 0 && x < I && y >= 0 && y < I;
	}
}

class Pair {
	int x;
	int y;

	Pair(int x, int y) {
		this.x = x;
		this.y = y;
	}
}