A matrix probability question ?


Here we will see one matrix probability problem. We have one rectangular matrix. We can move four directions from the current cell with equal probability. These four directions are left, right, up and down. We have to calculate the probability after N moves from position M[i, j].

Here we will do something related to DFS. We will traverse recursively traverse in each of the four possible rooms from the current room. Then we will calculate the probability with one less move. As each of the four directions has equal probability, then each direction will contribute 0.25 of total probability. If we cross the matrix boundary, we will return 0, and 1 will be returned when N move is completed. Let us see the algorithm to get the idea.

Algorithm

matProb(m, n, x, y, N)

Begin
   if x,y is not in matrix boundary m, n, then return 0
   if N is 0 , then return 1
   prob := 0
   prob := prob + matProb(m, n, x-1, y, N-1) * 0.25
   prob := prob + matProb(m, n, x+1, y, N-1) * 0.25
   prob := prob + matProb(m, n, x, y+1, N-1) * 0.25
   prob := prob + matProb(m, n, x, y-1, N-1) * 0.25
   return prob
End

Example

#include<iostream>
using namespace std;
bool isSafe(int x, int y, int m, int n) { //function to check whether (x,y)
   is in matrix or not
   if(x >= 0 && x < m && y >= 0 && y < n){
      return true;
   }
   return false;
}
double matProb(int m, int n, int x, int y, int N) {
   if (!isSafe(x, y, m, n)) //if coundary is crossed
      return 0.0;
   if (N == 0) //when N is 0, or N is completed, return 1
      return 1.0;
   double probability = 0.0;
   probability += matProb(m, n, x - 1, y, N - 1) * 0.25; //move left
   probability += matProb(m, n, x, y + 1, N - 1) * 0.25; //move up
   probability += matProb(m, n, x + 1, y, N - 1) * 0.25; //move right
   probability += matProb(m, n, x, y - 1, N - 1) * 0.25; //move down
   return probability;
}
int main() {
   int m = 7, n = 8;
   int x = 1, y = 1;
   int N = 4;
   cout << "Matrix Probability is " << matProb(m, n, x, y, N);
}

Output

Matrix Probability is 0.664062

Updated on: 31-Jul-2019

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements