The Fibonacci sequence is defined using the following recursive formula:
F(0) = 0 F(1) = 1 F(M) = F(M - 1) + F(M - 2) if M >= 2
A small frog wants to get to the other side of a river. The frog is initially located at one bank of the river (position −1) and wants to get to the other bank (position N). The frog can jump over any distance F(K), where F(K) is the K-th Fibonacci number. Luckily, there are many leaves on the river, and the frog can jump between the leaves, but only in the direction of the bank at position N.
The leaves on the river are represented in a zero-indexed array A consisting of N integers. Consecutive elements of array A represent consecutive positions from 0 to N − 1 on the river. Array A contains only 0s and/or 1s:
- 0 represents a position without a leaf;
- 1 represents a position containing a leaf.
The goal is to count the minimum number of jumps in which the frog can get to the other side of the river (from position −1 to position N). The frog can jump between positions −1 and N (the banks of the river) and every position containing a leaf.
For example, consider array A such that:
A[0] = 0 A[1] = 0 A[2] = 0 A[3] = 1 A[4] = 1 A[5] = 0 A[6] = 1 A[7] = 0 A[8] = 0 A[9] = 0 A[10] = 0
The frog can make three jumps of length F(5) = 5, F(3) = 2 and F(5) = 5.
Write a function:
int solution(vector<int> &A);
that, given a zero-indexed array A consisting of N integers, returns the minimum number of jumps by which the frog can get to the other side of the river. If the frog cannot reach the other side of the river, the function should return −1.
For example, given:
A[0] = 0 A[1] = 0 A[2] = 0 A[3] = 1 A[4] = 1 A[5] = 0 A[6] = 1 A[7] = 0 A[8] = 0 A[9] = 0 A[10] = 0
the function should return 3, as explained above.
思路:利用BFS。仅记录当前位置和下一跳位置,当下一跳位置为终点时算法结束,返回跳数。对下一跳位置用贪心算法,先尝试可能到达的最远的下一跳位置(与当前位置距离为Fibonacci值,该位置有荷叶),若以该位置为下一跳最终不可达到终点,则尝试可能到达的第二远的下一跳位置,算法如此进行,若不论以何位置为下一跳均不能到达终点,则返回-1.
代码:
// you can use includes, for example:
// #include
#include
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
vector
dynamicFibs(int n) {
vector
fibs;
fibs.push_back(0);
fibs.push_back(1);
for(int i=2;i
n+2) { break; } fibs.push_back(tmp); } return fibs; } int solution(vector
&A) { // write your code in C++11 const int size = A.size(); if(size==0) return 1; vector
fib = dynamicFibs(size); int fsize = fib.size(); vector
visited(size,0); int j = -1; //former index // int k = 0; //new index int cnt = 0; queue
q; q.push(j); queue
s; s.push(cnt); while(!q.empty()) { j = q.front(); q.pop(); cnt = s.front(); s.pop(); for(int i = fsize-1;i>=1;i--) { int k = j+fib[i]; if(k==size) { return cnt+1; } if(k>size||A[k]==0||visited[k]==1) { continue; } q.push(k); s.push(cnt+1); visited[k] = 1; } } return -1; }