• 문제 링크
12761번: 돌다리
동규와 주미는 일직선 상의 돌 다리 위에있다. 돌의 번호는 0 부터 100,000 까지 존재하고 동규는 \(N\)번 돌 위에, 주미는 \(M\)번 돌 위에 위치하고 있다. 동규는 주미가 너무 보고싶기 때문에 최대
www.acmicpc.net
• 풀이 과정
• 풀이 코드
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static int a, b, n, m;
static int[] dist;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
dist = new int[100001];
Arrays.fill(dist, 100000);
bw.write(String.valueOf(bfs()));
bw.flush();
}
private static int bfs() {
Queue<Integer> q = new LinkedList<>();
int[] dir = new int[]{1, -1, a, -a, b, -b, a, b};
q.offer(n);
dist[n] = 0;
while (!q.isEmpty()) {
int cur = q.poll();
if (cur == m)
break;
for (int i = 0; i < 8; i++) {
int next;
if (i < 6)
next = cur + dir[i];
else
next = cur * dir[i];
if (next < 0 || next > 100000 || dist[next] <= dist[cur] + 1)
continue;
dist[next] = dist[cur] + 1;
q.offer(next);
}
}
return dist[m];
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 14675 단절점과 단절선 - Graph Theory / Java (0) | 2023.03.07 |
---|---|
[백준] 15558 점프 게임 - Graph Theory / Java (0) | 2023.03.06 |
[백준] 16457 단풍잎 이야기 - Backtracking / Java (0) | 2023.03.04 |
[백준] 23284 모든 스택 수열 - Backtracking / Java (0) | 2023.03.03 |
[백준] 15270 친구 팰린드롬 - Backtracking / Java (0) | 2023.03.02 |
댓글