
https://www.acmicpc.net/problem/1697


1. 초기에는 시작 위치를 큐에 담고 방문한 배열로 체크한다
2. 큐가 비지 않는다면 다음을 반복한다
2.1 큐의 사이즈만큼 반복문을 돈다
- 큐에서 하나의 값을 꺼내어 동생의 위치(K)와 같은지 확인한다
- 같지 않다면 다음에 방문할 수 있는 위치들을 큐에 삽입한다
- 더하거나 빼거나 곱하거나 연산을 진행하고, 이때 배열의 범위를 벗어나지 않도록 if문으로 처리가 필요하다
2.2 반복문을 한 번 수행할 때마다 count를 통해 초를 증가시킨다
import java.io.*;
import java.util.*;
public class Main {
private static int N = 0;
private static int K = 0;
private static boolean[] visited;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] token = br.readLine().split(" ");
N = Integer.parseInt(token[0]);
K = Integer.parseInt(token[1]);
visited = new boolean[100001];
int answer = bfs();
System.out.println(answer);
}
private static int bfs() {
int count = 0;
Queue<Integer> queue = new LinkedList<>();
int[] num = {-1, 1, 2};
queue.add(N);
visited[N] = true;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i=0 ; i<size ; i++) {
int idx = queue.poll();
if(idx == K) {
return count;
}
for(int j=0; j<3 ; j++) {
int nextIdx;
if(j < 2) {
nextIdx = idx + num[j];
}
else {
nextIdx = idx * num[j];
}
if(nextIdx < 0 || nextIdx > 100000 || visited[nextIdx]) {
continue;
}
queue.add(nextIdx);
visited[nextIdx] = true;
}
}
count++;
}
return count;
}
}
연산자 순서로 인해 index out of bound를 만나 이를 기록하려한다
더하거나 빼거나 곱하거나 연산을 진행하고, 이때 배열의 범위를 벗어나지 않도록 if문으로 처리가 필요하다 라고 위의 설명에 써 두었는데, 다음에 방문할 위치의 index를 구했을 때 내가 정의해둔 visited 배열의 범위를 벗어날 수 있을 것이다
그래서 if(nextIdx < 0 || nextIdx> 100000 || visited[nextIdx])라는 조건문을 사용하고 있다
그러나 처음에는 다음과 같이 nextIdx > 100000보다 visited[nextIdx]를 먼저 작성했다
if(nextIdx < 0 || visited[nextIdx] || nextIdx> 100000)