There is an island represented by a matrix. You are somewhere on an island at (x,y) . If you jump n times, what is the likelihood that you will survive? Survival means that after jump n you must be on the island.
My solution: I applied the flood fill algorithm , in which I was allowed to move in all directions (i.e. N, W, E, S) and is checked if I was at the island before the n jumps, then increase the failure counter, otherwise increase the success counter.
After repeating all possible paths, the answer will be ((success) / (success + failure)). It takes exponential time.
My question is from you - can we solve this problem in polynomial time using dynamic programming or any other programming technique? If so, can you give me a concept for this technique?
EDIT: MY CODE
#include<iostream> using namespace std; double probability_of_survival(int n, int m, int x, int y, int jumps) { int success = 0; int failure = 0; probability_of_survival_utility_func(n, m, x, y, 0, jumps, &sucess, &failure); return (double)((success)/(failure+success)); } void probability_of_survival_utility_func(int n, int m, int x, int y, int jump_made, int jumps, int *success, int *failure) { if(x > m || x < 0 || y > n || y < 0) { (*failure)++; return;} if(jump_made == jumps) { (*success)++; return;} probability_of_survival_utility_func(n, m, x+1, y, jump_made++, jumps, success, failure); probability_of_survival_utility_func(n, m, x, y+1, jump_made++, jumps, success, failure); probability_of_survival_utility_func(n, m, x-1, y, jump_made++, jumps, success, failure); probability_of_survival_utility_func(n, m, x, y-1, jump_made++, jumps, success, failure); }