Jumping on the Clouds

HeeSeong·2021년 6월 27일
0

HackerRank

목록 보기
3/18
post-thumbnail

🔗 문제 링크

https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup


❔ 문제 설명


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):

  • int c[n]: an array of binary integers

Returns

  • int: the minimum number of jumps required

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 0in0 ≤ i ≤ n.


⚠️ 제한사항


  • 2n1002 ≤ n ≤ 100

  • c[i]0,1100c[i] ∈ {0, 1} 100

  • c[0]=c[n1]=0c[0] = c[n-1] = 0



💡 풀이 (언어 : Java)


무조건 성공하는 케이스가 존재한다고 문제에서 조건을 주었으므로, 단순하게 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));
	}
}
profile
끊임없이 성장하고 싶은 개발자

0개의 댓글