☑️ 문제: 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;
}
}
'TIL (Today I Learned)' 카테고리의 다른 글
99클럽 코테 스터디 33일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.24 |
---|---|
99클럽 코테 스터디 32일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.23 |
99클럽 코테 스터디 30일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.21 |
99클럽 코테 스터디 29일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.19 |
99클럽 코테 스터디 28일차 TIL + 오늘의 학습 키워드 (0) | 2024.08.19 |