728x90
https://www.acmicpc.net/problem/7562
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
풀이)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main_BJ_7562_나이트의이동 {
static int[] dx = {-1, -2, -2, -1, 1, 2, 2, 1};
static int[] dy = {-2, -1, 1, 2, 2, 1, -1, -2};
static int[][] map;
static boolean[][] visited;
static int l, endx, endy;
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
for(int tc=0; tc<t; tc++){
l = Integer.parseInt(br.readLine());
map = new int[l][l];
visited = new boolean[l][l];
StringTokenizer st = new StringTokenizer(br.readLine());
int curx = Integer.parseInt(st.nextToken());
int cury = Integer.parseInt(st.nextToken());
map[curx][cury] = 1;
st = new StringTokenizer(br.readLine());
endx = Integer.parseInt(st.nextToken());
endy = Integer.parseInt(st.nextToken());
int cnt = bfs(curx, cury);
System.out.println(cnt);
}//test case
}//main
private static int bfs(int x, int y){
Queue<int[]> q = new ArrayDeque<>();
visited[x][y] = true;
q.add(new int[] {x, y, 0});
while (!q.isEmpty()){
int[] cur = q.poll();
if(cur[0] == endx && cur[1] == endy)
return cur[2];
for(int i=0; i<8; i++){
int nx = cur[0]+dx[i];
int ny = cur[1]+dy[i];
if(check(nx, ny) && !visited[nx][ny]){
q.add(new int[] {nx, ny, cur[2]+1});
visited[nx][ny] = true;
}
}
}//while
return -1;
}//bfs
private static boolean check(int x, int y){
if(x<0 || y<0 || x>=l || y>=l)
return false;
return true;
}
}
BFS를 이용하면 쉽게 풀 수 있다!
이때, 나이트 위치 이동만 신경써서 dx, dy를 작성해주고, bfs코드에서도 queue 이동할 때 이동 숫자만 잘 체크해주면 된다.
그러면 간단하게 끝!
728x90
'코테 > 백준' 카테고리의 다른 글
백준 1316 그룹 단어 체커(JAVA) (0) | 2023.06.14 |
---|---|
백준 1713 후보 추천하기(JAVA) (0) | 2023.06.05 |
백준 1912 연속합(JAVA) (0) | 2023.06.03 |
백준 15651 N과 M(3) (JAVA) (0) | 2023.05.31 |
백준 11729 하노이 탑 이동 순서(JAVA) (0) | 2023.05.29 |