🐍Python/Python_알고리즘

[알고리즘] 46. Jumping on the Clouds

728x90
반응형

Emma is playing a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. She can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus  or . She must avoid the thunderheads. Determine the minimum number of jumps it will take Emma to jump from her starting postion to the last cloud. It is always possible to win the game.

For each game, Emma will get an array of clouds numbered  if they are safe or  if they must be avoided. For example,  indexed from . The number on each cloud is its index in the list so she must avoid the clouds at indexes  and . She could follow the following two paths:  or . The first path takes  jumps while the second takes .

Function Description

Complete the jumpingOnClouds function in the editor below. It should return the minimum number of jumps required, as an integer.

jumpingOnClouds has the following parameter(s):

  • c: an array of binary integers

Input Format

The first line contains an integer , the total number of clouds. The second line contains  space-separated binary integers describing clouds  where .

Constraints

Output Format

Print the minimum number of jumps needed to win the game.

Sample Input 0

7
0 0 1 0 0 1 0

Sample Output 0

4

Explanation 0:
Emma must avoid  and . She can win the game with a minimum of  jumps:

Sample Input 1

6
0 0 0 0 1 0

Sample Output 1

3

Explanation 1:
The only thundercloud to avoid is . Emma can win the game in  jumps:



답 : 


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the jumpingOnClouds function below.
if __name__ == '__main__':
n = int(input())
c = list(map(int, input().rstrip().split()))

count = 0
i = 0
while i < len(c)-2:
if c[i+1] == 0 and c[i+2]==1:
i += 1
count += 1
elif c[i+2] == 0:
i += 2
count += 1
if len(c[i:]) == 2:
print(count+1)
else:
print(count)



먼저 가능성을 두 가지로 열어놨다.


1) 한 칸 뒤는 0인데 두 칸 뒤는 1일 경우 한 칸만 전진가능하다.

2) 두 칸뒤가 0이면 한 칸 뒤가 뭐든 간에 무조건 두 칸 전진한다. 


칸을 전진하면서 전진한 만큼 i에 추가해주어 체스 말을 움직이듯이 움직였다. 그리고 마지막에 도출되는 i가 어디에 멈추는지에 따라 또 추가 된다. 


마지막은 무조건 0이라는 조건이 있었으므로 

만약에 i번째가 c[-1]의 바로 전이라면 +1을 하고

i가 딱 마지막, 즉 c[-1]이었다면 그대로의 count를 출력한다. 

728x90
반응형