기타/코딩테스트
(코테) 백준_1697_숨박꼭질 BFS
불광동 물주먹
2025. 5. 24. 19:16
package codingTest;
import java.util.*;
import java.io.*;
public class Backjun_1697_숨박꼭질 {
static int N,M; //N은 수빈 위치 M은 동생위치
static boolean[] visted = new boolean[100001];
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N=Integer.parseInt(st.nextToken());
M=Integer.parseInt(st.nextToken());
bfs(N);
}
public static void bfs(int now) {
Queue<int[]> q = new LinkedList<>();
visted[now] = true;
q.offer(new int[] {now,0});
while(!q.isEmpty()) {
int[] qList=q.poll();
int nowIndex = qList[0]; //현재 위치
int nowDeep = qList[1]; //현재 이동횟수
if(nowIndex==M) { // 종료
System.out.print(nowDeep);
return;
};
if(nowIndex*2 >= 0 && nowIndex*2 <= 100000 && !visted[nowIndex*2]) {
visted[nowIndex*2] = true;
q.offer(new int[] {nowIndex*2 , nowDeep+1});
}
if(nowIndex+1 >= 0 && nowIndex+1 <= 100000 && !visted[nowIndex+1]) {
visted[nowIndex+1] = true;
q.offer(new int[] {nowIndex+1 , nowDeep+1});
}
if(nowIndex-1 >= 0 && nowIndex-1 <= 100000 && !visted[nowIndex-1]) {
visted[nowIndex-1] = true;
q.offer(new int[] {nowIndex-1 , nowDeep+1});
}
/*
//for문으로 위 if 문 3개 반복되는거 줄일 수 있음.
for (int next : new int[]{nowIndex - 1, nowIndex + 1, nowIndex * 2}) {
if (next >= 0 && next <= 100000 && !visited[next]) {
visited[next] = true;
q.offer(new int[]{next, nowDeep + 1});
}
}
*/
}
}
}