There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus 1 or 2. The player must avoid the thunderheads. Determine the minimum number of jumps it will take to jump from the starting postion to the last cloud. It is always possible to win the game.
For each game, you will get an array of clouds numbered 0 if they are safe or 1 if they must be avoided.
Example
Index the array from 0..6. The number on each cloud is its index in the list so the player must avoid the clouds at indices 1 and 5. They could follow these two paths: 0 - 2 - 4 - 6 or 0 - 2 - 3 - 4 - 6. The first path takes 3 jumps while the second takes 4. Return 3.
Function Description
Complete the jumpingOnClouds function in the editor below.
jumpingOnClouds has the following parameter(s):
Returns
Input Format
The first line contains an integer , the total number of clouds. The second line contains space-separated binary integers describing clouds c[i] where .
무조건 성공하는 케이스가 존재한다고 문제에서 조건을 주었으므로, 단순하게 2칸 앞으로 갈 수 있으면 2칸가고, 못가면 1칸만 앞으로 가는 알고리즘을 작성하면 된다. 인덱스가 리스트 마지막 원소의 인덱스거나 그 이상의 값이면 종료한다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
private static int jumpingOnClouds (int n, String[] cloudList) {
int answer = 0;
int idx = 0;
while (idx < n-1) {
idx = (idx <= n-3 && cloudList[idx+2].equals("0")) ? idx + 2 : idx + 1;
answer += 1;
}
return answer;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] cloudList = br.readLine().split(" ");
System.out.println(jumpingOnClouds(n, cloudList));
}
}