새소식

알고리즘/문제

[BOJ/백준 - 1697] 숨바꼭질

  • -

문제 출처: https://www.acmicpc.net/problem/1697

 

1697번: 숨바꼭질

수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일

www.acmicpc.net

 


public class BOJ_TEMP {
public static void main(String[] args) throws Exception{
// INPUT & INIT
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
if(a > b) {
System.out.println(a - b);
return;
}else if (a == b) {
System.out.println(0);
return;
}
int[] arr = new int[100001];
int target = a;
Queue<Integer> q = new LinkedList<>();
q.add(target);
while(!q.isEmpty()) {
int cur = q.poll();
for(int i=0; i<3; i++) {
int next = 0;
if(i==0) {
next = cur-1;
}else if(i==1) {
next = cur+1;
}else {
next = cur*2;
}
if(0 <= next && next <= 100000 && arr[next] == 0) {
arr[next] = arr[cur]+1;
q.add(next);
}
}
}
System.out.println(arr[b]);
}
}
view raw BOJ_1697.java hosted with ❤ by GitHub

기본적인 형태의 BFS풀이로 진행

Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.