728x90
반응형
bfs 간단한 문제
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Point{
int x,y;
public Point(int x,int y){
this.x = x;
this.y = y;
}
}
public class Main {
static int dx[] = {-1,-2,-2,-1,1,2,2,1};
static int dy[] = {-2,-1,1,2,2,1,-1,-2};
static int [][] arr;
static boolean [][] check;
static int x,y,ex,ey,N;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while (T-->0){
N = Integer.parseInt(br.readLine());
arr = new int[N][N];
check = new boolean[N][N];
StringTokenizer st = new StringTokenizer(br.readLine()," ");
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
check[x][y] = true;
st = new StringTokenizer(br.readLine()," ");
ex = Integer.parseInt(st.nextToken());
ey = Integer.parseInt(st.nextToken());
bfs();
}
}
private static void bfs() {
Queue<Point> q = new LinkedList<>();
q.offer(new Point(x,y));
while (!q.isEmpty()){
int len = q.size();
for (int j = 0; j < len; j++) {
Point poll = q.poll();
if(poll.x == ex && poll.y == ey){
break;
}
for (int i = 0; i < 8; i++) {
int nx = poll.x + dx[i];
int ny = poll.y + dy[i];
// 범위 체크
if(0<= nx && nx < N && 0<= ny && ny < N){
// 방문 체크
if(!check[nx][ny] && arr[nx][ny]==0){
check[nx][ny] = true;
arr[nx][ny] = arr[poll.x][poll.y]+1;
q.offer(new Point(nx,ny));
}
}
}
}
}
System.out.println(arr[ex][ey]);
}
}
728x90
반응형
'알고리즘 > DFS, BFS, 시뮬, 백트래킹' 카테고리의 다른 글
[백준] 24479번 알고리즘 수업 - 깊이 우선 탐색 1 #Java (0) | 2022.06.17 |
---|---|
[백준] 2578번 빙고 #Java (0) | 2022.05.25 |
[백준] 2630번 색종이 만들기 (0) | 2022.05.17 |
[알고리즘] 미로탐색(DFS) with Java, 초기화 전략 (0) | 2022.04.22 |
[프로그래머스] N-Queen 문제 (0) | 2021.11.09 |