-
[Java] BOJ 1326 폴짝폴짝개발자 취업/코딩테스트 준비 2023. 6. 2. 16:37반응형
1326번: 폴짝폴짝
첫째 줄에 징검다리의 개수 N(1≤N≤10,000)이 주어지고, 이어서 각 징검다리에 쓰여 있는 N개의 정수가 주어진다. 그 다음 줄에는 N보다 작거나 같은 자연수 a, b가 주어지는 데, 이는 개구리가 a번
www.acmicpc.net
오답 코드
- 점프 할 수 있는 방향이 양수로만 생각해서 오답
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static StringTokenizer st; static int N; static int[] arr; static int[] visit; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine(), " "); arr = new int[N + 1]; for (int i = 1; i <= N; i++) { arr[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine(), " "); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); System.out.println(BFS(a, b)); } private static int BFS(int a, int b) { visit = new int[N + 1]; Arrays.fill(visit, Integer.MAX_VALUE); Queue<int[]> queue = new LinkedList<>(); queue.add(new int[] { a, 0 }); visit[a] = 0; while (!queue.isEmpty()) { int[] now = queue.poll(); if (now[0] == b) { return now[1]; } for (int i = now[0]; i <= N; i += arr[now[0]]) { if (now[1] + 1 < visit[i]) { visit[i] = now[1] + 1; queue.add(new int[] { i, now[1] + 1 }); } } } return -1; } }
정답 코드
- 점프 할 수 있는 방향이 음수 / 양수 방향 가능
import java.io.*; import java.util.*; public class Main { static BufferedReader br; static StringTokenizer st; static int N; static int[] arr; static int[] visit; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); N = Integer.parseInt(br.readLine()); st = new StringTokenizer(br.readLine(), " "); arr = new int[N + 1]; for (int i = 1; i <= N; i++) { arr[i] = Integer.parseInt(st.nextToken()); } st = new StringTokenizer(br.readLine(), " "); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); System.out.println(BFS(a, b)); } private static int BFS(int a, int b) { visit = new int[N + 1]; Arrays.fill(visit, Integer.MAX_VALUE); Queue<int[]> queue = new LinkedList<>(); queue.add(new int[] { a, 0 }); visit[a] = 0; while (!queue.isEmpty()) { int[] now = queue.poll(); if (now[0] == b) { return now[1]; } for (int i = now[0]; i > 0; i -= arr[now[0]]) { if (now[1] + 1 < visit[i]) { visit[i] = now[1] + 1; queue.add(new int[] { i, now[1] + 1 }); } } for (int i = now[0]; i <= N; i += arr[now[0]]) { if (now[1] + 1 < visit[i]) { visit[i] = now[1] + 1; queue.add(new int[] { i, now[1] + 1 }); } } } return -1; } }
'개발자 취업 > 코딩테스트 준비' 카테고리의 다른 글
[Java] BOJ 12873 기념품 (0) 2023.06.04 [Java] BOJ 1342 행운의 문자열 (0) 2023.06.03 [Java] BOJ 21966 중략 (0) 2023.06.01 [Java] BOJ 14916 거스름돈 (0) 2023.06.01 [Java] BOJ 1927 최소 힙 (0) 2023.05.26