CS/Algorithm

[백준 : 7562] 나이트의 이동 - JAVA

yujindonut 2021. 5. 23. 20:08
728x90

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class Dot{
	int x;
	int y;
	int count;
	public Dot(int x, int y) {
		this.x = x;
		this.y = y;
	}
	public Dot(int x, int y, int count) {
		this.x = x;
		this.y = y;
		this.count = count;
	}
}
public class Main {
	static int map[][]; // 2차원 미로 배열
	static boolean visit[][]; // 2차원 방문여부 배열
	static int N;
	static Dot[] dots;
	static int[] dx = {-2,-2,-1,-1,1,1,2,2};
	static int[] dy = {-1,1,-2,2,2,-2,1,-1};
	
	public static int bfs() { //BFS메소드
		
		Queue<Dot> q = new LinkedList<>();
		q.offer(dots[0]); 
		visit[dots[0].x][dots[0].y] = true;
		
		while(!q.isEmpty()) {
			
			Dot d = q.poll();

			if(d.x == dots[1].x && d.y == dots[1].y)
				return d.count;
			
			//상하좌우 8방향 노드 범위 벗어나는지 탐색
			for(int i = 0; i < 8; i++) {
				int qx = d.x + dx[i];
				int qy = d.y + dy[i];
				
				if(qx >= 0 && qx < N && qy >= 0 && qy < N)
					if(!visit[qx][qy]) {
						q.add(new Dot(qx,qy,d.count + 1));
						visit[qx][qy] = true;
					}
			}
		}
		return -1;
	}
	public static void main(String[] args) throws IOException {
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int T = Integer.parseInt(br.readLine());
		
		for(int tc = 1; tc <= T; tc++) {			
			StringTokenizer st = new StringTokenizer(br.readLine());
			N = Integer.parseInt(st.nextToken());
			
			map = new int[N][N];
			visit = new boolean[N][N];
			dots = new Dot[2];
			for(int i = 0; i < 2; i++) {
				st = new StringTokenizer(br.readLine());
				int x = Integer.parseInt(st.nextToken());
				int y = Integer.parseInt(st.nextToken());
				
				dots[i] = new Dot(x,y);
			}
			System.out.println(bfs());
		}
	}
}

방문 count를 클래스 안에서 구현하는 것

dot[] 배열을 만들어 0번째 인덱스에는 시작점, 1번째 인덱스에는 마지막지점을 넣는 것

728x90