곽로그
[백준 7562,Java] 나이트의 이동 본문
반응형
문제
풀이
코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Point {
int x;
int y;
int moveCount;
Point(int x, int y, int moveCount){
this.x = x;
this.y = y;
this.moveCount = moveCount;
}
}
public class Main {
public static int T;
public static int N;
public static boolean visited[][];
public static int[] dx = {-2,-1,1,2,2,1,-1,-2};
public static int[] dy = {1,2,2,1,-1,-2,-2,-1};
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
T = Integer.parseInt(br.readLine());
for(int t = 0; t< T; t++){
N = Integer.parseInt(br.readLine());
visited = new boolean[N][N];
st = new StringTokenizer(br.readLine()," ");
int startX = Integer.parseInt(st.nextToken());
int startY = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine()," ");
int endX = Integer.parseInt(st.nextToken());
int endY = Integer.parseInt(st.nextToken());
int result = getMoveCount(startX, startY, endX, endY);
bw.write(String.valueOf(result)+"\n");
}
bw.flush();
br.close();
bw.close();
}
public static int getMoveCount(int startX, int startY, int endX, int endY){
int totalCount = 0;
//초기화
visited[startX][startY] = true;
Point kinght = new Point(startX, startY, 0);
Queue<Point> queue = new LinkedList<>();
queue.add(kinght);
//bfs
while(!queue.isEmpty()){
Point currentKnight = queue.poll();
if(currentKnight.x == endX && currentKnight.y ==endY){
totalCount = currentKnight.moveCount;
}
else{
for(int d =0; d<8; d++){
int nx = currentKnight.x + dx[d];
int ny = currentKnight.y + dy[d];
int nc = currentKnight.moveCount +1;
if(nx>=0 && ny>=0 && nx<N && ny<N){
if(!visited[nx][ny]){
Point nextKignht = new Point(nx, ny, nc);
queue.add(nextKignht);
visited[nx][ny] = true;
}
}
}
}
}
return totalCount;
}
}
반응형
'알고리즘 > 백준' 카테고리의 다른 글
[백준 11724, Java] 연결 요소의 개수 (0) | 2020.12.28 |
---|---|
[백준 4963, Java] 섬의 개수 (0) | 2020.12.28 |
[백준 16236, Java] 아기상어 (0) | 2020.12.28 |
[백준 7576,Java] 토마토 (0) | 2020.12.28 |
[백준 13300, Java] 방 배정 (0) | 2020.12.23 |
Comments