728x90
8. 송아지 찾기 1(BFS : 상태트리탐색)
https://cote.inflearn.com/contest/10/problem/07-08
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[] dis = {-1, 1, 5};
public static void main(String[] args){
Scanner sc =new Scanner(System.in);
int input1 = sc.nextInt();
int input2 = sc.nextInt();
BFS(input1, input2);
}
static void BFS(int input1, int input2) {
boolean[] check = new boolean[10001];
int level = 0;
Queue<Integer> queue = new LinkedList<>();
queue.offer(input1);
check[input1] = true;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i=0; i<size; i++) {
int x = queue.poll();
for(int k=0; k<3; k++) {
int newX = x + dis[k];
if(newX == input2) {
System.out.println(level+1);
return;
}
if(1 <=newX && newX<=10000 && check[newX]==false) {
check[newX] = true;
queue.offer(newX);
}
}
}
level++;
} // end of while
}
}
728x90
'[알고리즘] > 알고리즘' 카테고리의 다른 글
[알고리즘] 백준1159번 : 농구경기 (브론즈2) (0) | 2022.03.05 |
---|---|
[알고리즘] 백준 1260. DFS와 BFS (0) | 2022.02.23 |
[알고리즘] 백준 1759. 암호 만들기 (0) | 2022.02.22 |
[알고리즘] 백준 1182. 부분수열의 합 (0) | 2022.02.17 |
[알고리즘] SW Expert Acadamy 5215. 햄버거 다이어트 (0) | 2022.02.17 |