Boj 7562 나이트의 이동
Updated:
문제 링크 : 백준 https://www.acmicpc.net/problem/7562
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int N;
static int[][] map;
static boolean[][] visited;
static int x,y,end_x,end_y;
static int[] dx = {-2,-1,2,1,2,1,-2,-1};
static int[] dy = {1,2,1,2,-1,-2,-1,-2};
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int testCase = Integer.parseInt(br.readLine());
for (int tc = 0; tc < testCase; tc++) {
N = Integer.parseInt(br.readLine());
map = new int[N][N];
visited = new boolean[N][N];
st =new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
st =new StringTokenizer(br.readLine());
end_x = Integer.parseInt(st.nextToken());
end_y = Integer.parseInt(st.nextToken());
bfs();
System.out.println(map[end_x][end_y]);
}
}
private static void bfs() {
Queue<point> q= new LinkedList<>();
q.add(new point(x, y));
visited[x][y]=true;
while(!q.isEmpty()) {
point temp = q.poll();
int x = temp.x;
int y = temp.y;
if(x==end_x && y==end_y) {
break;
}
for (int i = 0; i < 8; i++) {
int cx = x+dx[i];
int cy = y+dy[i];
if(cx>=0 && cx<N && cy>=0 && cy<N&&!visited[cx][cy]) {
q.add(new point(cx,cy));
visited[cx][cy]=true;
map[cx][cy]=map[x][y]+1;
}
}
}
}
static class point{
int x;
int y;
public point(int x, int y) {
super();
this.x = x;
this.y = y;
}
}
}
Leave a comment