❗ 풀이 과정
- BFS를 활용해서 풀면 된다.
- 처음에 풀이할 때에는 queue에 다 집어넣고 완전탐색으로 풀면 되지 않을까? 했지만,, 메모리 초과가 났다
- visited 배열을 활용해, 방문한 위치는 다시 탐색하지 않도록 제한을 걸어두고 했더니 성공!
😥 메모리 초과 났던 코드
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
int cnt = 0;
int result = 0;
Queue<Integer> queue = new LinkedList<Integer>();
if(N==K) {
System.out.println(0);
}
else {
queue.offer(N);
while(queue.size()>0) {
cnt++;
int tmp = queue.poll();
if(tmp-1 == K || tmp+1 == K || tmp*2 == K) {
break;
}
queue.offer(tmp-1);
queue.offer(tmp+1);
queue.offer(tmp*2);
}
int i=0;
while(cnt>0) {
result++;
cnt-=Math.pow(3,i);
i++;
}
System.out.println(result);
}
sc.close();
}
}
🤜 풀이 코드
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main_1697_숨바꼭질 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int K = sc.nextInt();
int [] visited = new int [100001];
Queue<Integer> queue = new LinkedList<Integer>();
visited[N]=1;
if(N==K) {
System.out.println(0);
}
else {
queue.offer(N);
while(queue.size()>0) {
int tmp = queue.poll();
if(tmp-1 == K || tmp+1 == K || tmp*2 == K) {
System.out.println(visited[tmp]);
break;
}
if(tmp-1>=0 && visited[tmp-1]==0) {
queue.offer(tmp-1);
visited[tmp-1]=visited[tmp]+1;
}
if(tmp+1<100001 && visited[tmp+1]==0) {
queue.offer(tmp+1);
visited[tmp+1]=visited[tmp]+1;
}
if(tmp*2<100001 && visited[tmp*2]==0) {
queue.offer(tmp*2);
visited[tmp*2]=visited[tmp]+1;
}
}
}
sc.close();
}
}