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;
	}
}
'ALGORITHM > 프로그래머스 | 백준 | 삼성 | 카카오' 카테고리의 다른 글
| [백준] 9372번 상근이의 여행 (0) | 2020.07.29 | 
|---|---|
| [백준] 11403번 경로 찾기 (0) | 2020.07.29 | 
| [백준] 2644번 촌수계산 (0) | 2020.06.26 | 
| [프로그래머스] 전화번호 목록 (0) | 2020.06.20 | 
| [프로그래머스] 기능개발 (0) | 2020.06.18 |