백준 1697번
https://www.acmicpc.net/problem/1697
1697번: 숨바꼭질
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일
www.acmicpc.net
문제설명
x+1, x-1 , x*2로 움직이는 좌표를 계산해서 BFS
접근
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;
public class Main {
static Queue<Integer> q = new LinkedList<>();
static int[] map = new int[100001];
static int n,m;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk = new StringTokenizer(br.readLine());
n = Integer.parseInt(tk.nextToken());
m = Integer.parseInt(tk.nextToken());
map[n] = 1;
q.offer(n);
while (!q.isEmpty()) {
int nx;
int t = q.poll();
if(t == m){
System.out.println(map[t]-1);
}
for(int i=0;i<3;i++){
if(i==0){
nx = t+1;
}else if(i==1){
nx = t-1;
}else{
nx = t*2;
}
if(nx<0 || nx > 100000 || map[nx]!=0) continue;
q.offer(nx);
map[nx] = map[t]+1;
}
}
}
}
'알고리즘 > 백준 Baekjoon' 카테고리의 다른 글
백준 7562 나이트의 이동(JAVA) - BFS (0) | 2023.03.25 |
---|---|
백준 10026 적록색약(JAVA) - BFS (0) | 2023.03.25 |
백준 1926번 그림(JAVA) - BFS (0) | 2023.03.22 |
(LEVEL 2)프로그래머스 - 튜플 (JAVA) [2019 카카오 개발자 겨울 인턴십] (0) | 2023.03.13 |
백준 4963번 섬의 개수(JAVA) - DFS (0) | 2023.02.19 |