TIL (Today I Learned)

99클럽 코테 스터디 31일차 TIL + 오늘의 학습 키워드

남 희 2024. 8. 21. 21:55

☑️ 문제: 14248번: 점프 점프

https://www.acmicpc.net/problem/14248

 

☑️ 핵심 Code: BFS 풀이

    static void bfs() {
        boolean[] visited = new boolean[n];
        Queue<Integer> queue = new LinkedList<>();
        
        visited[startIndex] = true;
        queue.offer(startIndex);
        answer = 1;

        while(!queue.isEmpty()) {
            int index = queue.poll();
            int jump = stones[index];
            if (index - jump >= 0 && !visited[index - jump]) {
                visited[index - jump] = true;
                queue.offer(index - jump);
                answer++;
            }
            if (index + jump < n && !visited[index + jump]) {
                visited[index + jump] = true;
                queue.offer(index + jump);
                answer++;
            }
        }
    }

 

전체 코드

import java.util.*;

public class Main {
    static int n, startIndex, answer;
    static int[] stones;

    public static void main(String args[]) {
        input();
        bfs();
        System.out.println(answer);
    }
    
    static void bfs() {
        boolean[] visited = new boolean[n];
        Queue<Integer> queue = new LinkedList<>();
        
        visited[startIndex] = true;
        queue.offer(startIndex);
        answer = 1;

        while(!queue.isEmpty()) {
            int index = queue.poll();
            int jump = stones[index];
            if (index - jump >= 0 && !visited[index - jump]) {
                visited[index - jump] = true;
                queue.offer(index - jump);
                answer++;
            }
            if (index + jump < n && !visited[index + jump]) {
                visited[index + jump] = true;
                queue.offer(index + jump);
                answer++;
            }
        }
    }
    
    static void input() {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        stones = new int[n];
        for (int i = 0; i < n; i++) {
            stones[i] = sc.nextInt();
        }
        startIndex = sc.nextInt() - 1;        
    }
}