Jun's Development Journey
[BOJ] 13913 숨바꼭질 4 본문
문제
13913번: 숨바꼭질 4
수빈이는 동생과 숨바꼭질을 하고 있다. 수빈이는 현재 점 N(0 ≤ N ≤ 100,000)에 있고, 동생은 점 K(0 ≤ K ≤ 100,000)에 있다. 수빈이는 걷거나 순간이동을 할 수 있다. 만약, 수빈이의 위치가 X일
www.acmicpc.net
풀이
import java.io.*;
import java.util.*;
public class Main {
static int N,M;
static Queue<Integer> queue;
static int[] visit;
static int[] parent;
static void bfs(int st, int des) {
parent[st] = st;
visit[st] = 1;
queue.add(st);
while(!queue.isEmpty()) {
int std = queue.poll();
int next;
if(std == des) {
System.out.println(visit[std]-1);
Stack<Integer> path = new Stack<Integer>();
while(parent[std]!=std) {
path.push(std);
std = parent[std];
}
path.push(std);
StringBuilder sb = new StringBuilder();
while(!path.isEmpty()) {
sb.append(path.pop()+" ");
}
System.out.println(sb);
break;
}
next = std*2;
if(next<=100000 && visit[next]==0) {
visit[next] = visit[std]+1;
parent[next] = std;
queue.add(next);
}
next = std+1;
if(next<=100000 && visit[next]==0) {
visit[next] = visit[std]+1;
parent[next] = std;
queue.add(next);
}
next = std-1;
if(next>=0 && visit[next]==0) {
visit[next] = visit[std]+1;
parent[next] = std;
queue.add(next);
}
}
}
public static void main(String[] args) throws IOException {
//선언 및 입력
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> left = new ArrayList<Integer>();
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
queue = new LinkedList<Integer>();
visit = new int[100001];
parent = new int[100001];
//계산
bfs(N,M);
}
}
'BOJ > BFS' 카테고리의 다른 글
[BOJ] 16956 늑대와 양 (0) | 2021.04.07 |
---|---|
[BOJ] 17836번 공주님을 구해라! (0) | 2021.04.06 |
[BOJ] 9372 상근이의 여행 (0) | 2021.02.26 |