A matrix probability question in C?

Server Side ProgrammingProgramming

The matrix probability question Calculates the probability that whether an element will be inside the given matrix after taking N steps and any direction. This means we need to find what is the probability of an element not going out of the scope of the matrix even after moving N positions in any direction.

In this problem, we are free to move the matrix element in all four directions (left, right, up, down). And the probability of moving elements is same 0.25 or 1/4.

The program will return 0 if the element steps out otherwise not.

Example

 Live Demo

#include <stdio.h>
int isSafe(int x, int y, int m, int n) {
   return (x >= 0 && x < m &&
   y >= 0 && y < n);
}
double Probability(int m, int n, int x, int y, int N) {
   if (!isSafe(x, y, m, n))
      return 0.0;
   if (N == 0)
      return 1.0;
   double prob = 0.0;
   prob += Probability(m, n, x - 1, y, N - 1) * 0.25;
   prob += Probability(m, n, x, y + 1, N - 1) * 0.25;
   prob += Probability(m, n, x + 1,y, N - 1) * 0.25;
   prob += Probability(m, n, x, y - 1, N - 1) * 0.25;
   return prob;
}
int main() {
   int m = 5, n = 5;
   int i = 2, j = 1;
   int N = 4;
   printf("Probability of moving is %lf", Probability(m, n, i, j, N));
   return 0;
}

Output

Probability of moving is 0.738281
raja
Published on 04-Oct-2019 07:01:16
Advertisements