A matrix probability question ?

This problem calculates the probability of staying within a matrix after N moves from a given position. From any cell, we can move in four directions (left, right, up, down) with equal probability (0.25 each). If we cross the matrix boundary, the probability becomes 0.

Syntax

double matProb(int m, int n, int x, int y, int N);
int isSafe(int x, int y, int m, int n);

Parameters

  • m, n − Matrix dimensions (m rows, n columns)
  • x, y − Starting position coordinates
  • N − Number of moves to make

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

Here's the complete C implementation using recursive approach −

#include <stdio.h>

int isSafe(int x, int y, int m, int n) {
    if (x >= 0 && x < m && y >= 0 && y < n) {
        return 1;
    }
    return 0;
}

double matProb(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 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;
    
    printf("Matrix Probability is %.6f
", matProb(m, n, x, y, N)); return 0; }
Matrix Probability is 0.664062

How It Works

The algorithm uses divide-and-conquer approach −

  • Base case 1: If position goes outside matrix boundaries, return 0 (impossible)
  • Base case 2: If N moves are completed while staying inside, return 1 (success)
  • Recursive case: Try all 4 directions, each contributing 25% to total probability

Time Complexity

The time complexity is O(4^N) as each recursive call branches into 4 directions. For optimization, memoization can be used to reduce complexity to O(m × n × N).

Conclusion

This recursive solution calculates matrix probability by exploring all possible paths. The probability decreases as we increase moves or start closer to boundaries, making it useful for random walk problems.

Updated on: 2026-03-15T11:09:31+05:30

244 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements