우당탕탕 개발자 되기
백준_나이트의 이동(7562) in Java 본문
https://www.acmicpc.net/problem/7562
7562번: 나이트의 이동
체스판 위에 한 나이트가 놓여져 있다. 나이트가 한 번에 이동할 수 있는 칸은 아래 그림에 나와있다. 나이트가 이동하려고 하는 칸이 주어진다. 나이트는 몇 번 움직이면 이 칸으로 이동할 수
www.acmicpc.net
풀이
- 일반적인 BFS 문제에서 나이트가 이동할 수 있는 범위가 다르기때문에 그에 맞춰 배열을 만들어준다
- 이동할때 배열에 +1 씩 해줘 이동횟수를 기록한다.
- 목표지점에 도착하면 그 배열의 값을 출력한다.
- 출발점과 시작 점이 같으면 0을 출력하게한다.
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[] dx = {2, 1, 2, 1, -2, -1, -2, -1};
static int[] dy = {1, 2, -1, -2, 1, 2, -1, -2};
static int[][] cnt;
static boolean[][] visited;
static int a;
static XY start, finish;
static Queue<XY> que = new LinkedList<>();
static class XY{
int x;
int y;
public XY(int x,int y) {
this.x = x;
this.y=y;
}
}
static int bfs(){
que = new LinkedList<>();
que.offer(start);
visited[start.x][start.y] = true;
while (!que.isEmpty()){
XY tmp = que.poll();
if(tmp.x== finish.x&&tmp.y== finish.y) {
return cnt[tmp.x][tmp.y];
}
for (int i = 0; i < 8; i++) {
int cx = tmp.x + dx[i];
int cy = tmp.y + dy[i];
if(0<=cx&&cx<a&&0<=cy&&cy<a){
if(!visited[cx][cy]){
visited[cx][cy]=true;
cnt[cx][cy]=cnt[tmp.x][tmp.y]+1;
que.offer(new XY(cx, cy));
}
}
}
}
return 0;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
for(int i=0;i<T;i++){
a = Integer.parseInt(br.readLine());
cnt= new int[a][a];
visited = new boolean[a][a];
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
start = new XY(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
st = new StringTokenizer(br.readLine(), " ");
finish = new XY(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
if(start.x== finish.x&&start.y== finish.y){
System.out.println(0);
}else{
System.out.println(bfs());
}
}
}
}
- 테스트 횟수가 1이상일수도 있기 때문에 bfs()를 시작할때는 초기화 해줘야 된다는 것을 생각하지못해서 마지막에 어려웠다.
'자료구조&알고리즘' 카테고리의 다른 글
| 프로그래머스 카카오 로또의 최고 순위와 최저 순위 (0) | 2021.09.30 |
|---|---|
| 프로그래머스 카카오 실패율 (0) | 2021.09.30 |
| 백준_전깃줄(2565) In Java (0) | 2021.08.02 |
| 백준_가장 큰 증가 부분수열(11055) In Java (0) | 2021.08.02 |
| 백준_가장 긴 증가하는 부분 수열(11053) In Java (0) | 2021.08.02 |