넓이 우선 탐색문제이다
만약 사람 h가 있고 송아지 c가 좌표 위 일직선상에 존재한다
h는 1, -1, 5밖에 이동을 하지 못한다
이때 c에 도달하는 최단거리는?
s는 c보다 작고 s와 c는 1이상 10000이하이다
만약 h가 5, c가 14일때

public class FindCalf {
//송아지 찾기 bfs
static int bfs(int h, int c) {
int[] arr = {1,-1,5};
HashSet<Integer> check = new HashSet<>(); //한번 넣은 수는 안넣게 하는 체크 배열
Queue<Integer> q = new LinkedList<>();
q.offer(h);
int l = 0;
while (!q.isEmpty()) {
int length = q.size();
for(int i=0; i<length; i++) {
int num = q.poll();
if(c == num) return l;
for(int x : arr) {
int nx = num + x;
if(nx >= 1 && nx <= 10000 && !check.contains(nx)) {
check.add(nx);
q.offer(nx);
}
}
}
l++;
}
return l;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int human = sc.nextInt();
int calf = sc.nextInt();
System.out.println(bfs(human,calf));
}
}
dfs와 bfs중 시간복잡도가 적을 가능성이 높은것을 생각하는 사고
bfs구현에서 시간복잡도를 줄이기위한 if문처리 실패 (hash를 이용한 중복제거)
항상 시간복잡도를 최선으로 줄이기를 노력하기
dfs, bfs둘 다 생각해보기