https://www.acmicpc.net/problem/1697
🌕 최종코드
import java.io.*;
import java.util.*;
public class Main{
static int subin;
static int sister;
static int result = Integer.MAX_VALUE;
static int[] visited;
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
subin = Integer.parseInt(st.nextToken());
sister = Integer.parseInt(st.nextToken());
if(subin == sister)
{
System.out.println(0);
return;
}
visited = new int[100001];
System.out.println(BFS(subin));
}
public static int BFS(int n)
{
Queue<Integer> que = new LinkedList<>();
que.add(n);
visited[n] = 1;
while(!que.isEmpty())
{
int x = que.remove();
if(x == sister)
{
return visited[x]-1;
}
if(2*x<=100000 && visited[2*x] == 0)
{
que.add(2*x);
visited[2*x] = visited[x]+1;
}
//뒤로 걷기
if(x-1 >= 0 && visited[x-1] == 0)
{
que.add(x-1);
visited[x-1] = visited[x]+1;
}
//앞으로 걷기
if(x+1<=100000 && visited[x+1] == 0)
{
que.add(x+1);
visited[x+1] = visited[x]+1;
}
}
return 0;
}
}
'항해' 카테고리의 다른 글
[DAY45] 99클럽 코딩테스트 JAVA 백준 이분 그래프 1707번 (1) | 2025.01.24 |
---|---|
[DAY44] 99클럽 코딩테스트 JAVA 백준 단지번호붙이기 2667번 (DFS/BFS) +런타임 에러 (1) | 2025.01.22 |
[DAY42] 99클럽 코딩테스트 JAVA 백준 DFS와 BFS 1260번 (1) | 2025.01.20 |
[DAY41] 99클럽 코딩테스트 JAVA 백준 두 용색 2470번 (0) | 2025.01.17 |
[DAY40] 99클럽 코딩테스트 JAVA 백준 기타 레슨 2343번 (0) | 2025.01.16 |