송아지 구하기 문제(BFS)

Changwook Yang·2023년 1월 7일

알고리즘 연습

목록 보기
1/41

송아지 구하기 문제(BFS)
이동할 수 있는 거리의 경우의 수는 1, -1, 5

public class Test230106 {

    static int[] checked = new int[10001];
    static int[] jumps = {1, -1, 5};
    public static int bfs(int s, int e) {

        Queue<Integer> queue = new LinkedList<>();
        queue.add(s);
        checked[s] = 1;

        int count = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                Integer position = queue.poll();
                if (position == e)
                    return count;

                for (int jump : jumps) {
                    int jumpedPosition = position + jump;
                    if(jumpedPosition > 0 && checked[jumpedPosition] == 0) {
                        checked[jumpedPosition] = 1;
                        queue.add(jumpedPosition);
                    }
                }
            }
            count++;
        }
        return 0;
    }
}
profile
멋있는 백엔드 개발자 / 꾸준히 의미있게!

0개의 댓글