A matrix probability question - GeeksforGeeks

27 Apr, 2021
Given a rectangular matrix, we can move from current cell in 4 directions with equal probability. The 4 directions are right, left, top or bottom. Calculate the Probability that after N moves from a given position (i, j) in the matrix, we will not cross boundaries of the matrix at any point.We strongly recommend you to minimize your browser and try this yourself first.The idea is to perform something similar to DFS. We recursively traverse in each of the 4 allowed direction and for each cell encountered, we calculate the required probability with one less move. As each direction has equal probability, each direction will contribute to 1/4 of total probability of that cell i.e. 0.25. We return 0 if we step outside the matrix and return 1 if N steps are completed without crossing matrix boundaries.Below is the implementation of above idea :  
C++
Java
Python3
C#
PHP
Javascript
/// C++ program to find the probability// that we do not cross boundary of a// matrix after N moves.#include <bits/stdc++.h>using namespace std; // check if (x, y) is valid matrix coordinatebool isSafe(int x, int y, int m, int n){    return (x >= 0 && x < m &&            y >= 0 && y < n);} // Function to calculate probability// that after N moves from a given// position (x, y) in m x n matrix,// boundaries of the matrix will not be crossed.double findProbability(int m, int n, int x,                       int y, int N){    // boundary crossed    if (!isSafe(x, y, m, n))        return 0.0;     // N steps taken    if (N == 0)        return 1.0;     // Initialize result    double prob = 0.0;     // move up    prob += findProbability(m, n, x - 1,                            y, N - 1) * 0.25;     // move right    prob += findProbability(m, n, x,                            y + 1, N - 1) * 0.25;     // move down    prob += findProbability(m, n, x + 1,                            y, N - 1) * 0.25;     // move left    prob += findProbability(m, n, x,                            y - 1, N - 1) * 0.25;     return prob;} // Driver codeint main(){    // matrix size    int m = 5, n = 5;     // coordinates of starting point    int i = 1, j = 1;     // Number of steps    int N = 2;     cout << "Probability is "        << findProbability(m, n, i, j, N);     return 0;}
// Java program to find the probability// that we do not cross boundary// of a matrix after N moves.import java.io.*; class GFG {     // check if (x, y) is valid// matrix coordinatestatic boolean isSafe(int x, int y,                      int m, int n){    return (x >= 0 && x < m &&            y >= 0 && y < n);} // Function to calculate probability// that after N moves from a given// position (x, y) in m x n matrix,// boundaries of the matrix will// not be crossed.static double findProbability(int m, int n,                              int x, int y,                              int N){         // boundary crossed    if (! isSafe(x, y, m, n))        return 0.0;     // N steps taken    if (N == 0)        return 1.0;     // Initialize result    double prob = 0.0;     // move up    prob += findProbability(m, n, x - 1,                            y, N - 1) * 0.25;     // move right    prob += findProbability(m, n, x, y + 1,                            N - 1) * 0.25;     // move down    prob += findProbability(m, n, x + 1,                            y, N - 1) * 0.25;     // move left    prob += findProbability(m, n, x, y - 1,                            N - 1) * 0.25;     return prob;} // Driver codepublic static void main (String[] args){    // matrix size    int m = 5, n = 5;     // coordinates of starting point    int i = 1, j = 1;     // Number of steps    int N = 2;     System.out.println("Probability is " +                       findProbability(m, n, i,                       j, N)); } } // This code is contributed by KRV.
# Python3 program to find the probability# that we do not cross boundary of a# matrix after N moves. # check if (x, y) is valid matrix coordinatedef isSafe(x, y, m, n):    return (x >= 0 and x < m and            y >= 0 and y < n) # Function to calculate probability# that after N moves from a given# position (x, y) in m x n matrix,# boundaries of the matrix will# not be crossed.def findProbability(m, n, x, y, N):         # boundary crossed    if (not isSafe(x, y, m, n)):        return 0.0     # N steps taken    if (N == 0):        return 1.0     # Initialize result    prob = 0.0     # move up    prob += findProbability(m, n, x - 1,                            y, N - 1) * 0.25     # move right    prob += findProbability(m, n, x,                            y + 1, N - 1) * 0.25     # move down    prob += findProbability(m, n, x + 1,                            y, N - 1) * 0.25     # move left    prob += findProbability(m, n, x,                            y - 1, N - 1) * 0.25     return prob # Driver codeif __name__ == '__main__':     # matrix size    m = 5    n = 5     # coordinates of starting po    i = 1    j = 1     # Number of steps    N = 2     print("Probability is",           findProbability(m, n, i, j, N)) # This code is contributed by PranchalK
// C# program to find the probability// that we do not cross boundary// of a matrix after N moves.using System; class GFG{     // check if (x, y) is valid// matrix coordinatestatic bool isSafe(int x, int y,                   int m, int n){    return (x >= 0 && x < m &&            y >= 0 && y < n);} // Function to calculate probability// that after N moves from a given// position (x, y) in m x n matrix,// boundaries of the matrix will// not be crossed.static double findProbability(int m, int n,                              int x, int y,                              int N){         // boundary crossed    if (! isSafe(x, y, m, n))        return 0.0;     // N steps taken    if (N == 0)        return 1.0;     // Initialize result    double prob = 0.0;     // move up    prob += findProbability(m, n, x - 1,                            y, N - 1) * 0.25;     // move right    prob += findProbability(m, n, x, y + 1,                            N - 1) * 0.25;     // move down    prob += findProbability(m, n, x + 1,                            y, N - 1) * 0.25;     // move left    prob += findProbability(m, n, x, y - 1,                            N - 1) * 0.25;     return prob;} // Driver codepublic static void Main (){    // matrix size    int m = 5, n = 5;     // coordinates of starting point    int i = 1, j = 1;     // Number of steps    int N = 2;     Console.Write("Probability is " +                   findProbability(m, n, i,                   j, N)); } } // This code is contributed by nitin mittal.
<?php// PHP program to find the probability// that we do not cross boundary of a// matrix after N moves. // check if (x, y) is valid// matrix coordinatefunction isSafe($x, $y, $m, $n){    return ($x >= 0 && $x < $m &&            $y >= 0 && $y < $n);} // Function to calculate probability// that after N moves from a given// position (x, y) in m x n matrix,// boundaries of the matrix will// not be crossed.function findProbability($m, $n, $x,                         $y, $N){    // boundary crossed    if (!isSafe($x, $y, $m, $n))        return 0.0;     // N steps taken    if ($N == 0)        return 1.0;     // Initialize result    $prob = 0.0;     // move up    $prob += findProbability($m, $n, $x - 1,                             $y, $N - 1) * 0.25;     // move right    $prob += findProbability($m, $n, $x,                             $y + 1, $N - 1) * 0.25;     // move down    $prob += findProbability($m, $n, $x + 1,                             $y, $N - 1) * 0.25;     // move left    $prob += findProbability($m, $n, $x,                             $y - 1, $N - 1) * 0.25;     return $prob;} // Driver code // matrix size$m = 5; $n = 5; // coordinates of starting point$i = 1; $j = 1; // Number of steps$N = 2; echo "Probability is ",      findProbability($m, $n, $i, $j, $N); // This code is contributed by nitin mittal.?>
<script>// JavaScript program to find the probability// that we do not cross boundary of a// matrix after N moves. // check if (x, y) is valid matrix coordinatefunction isSafe(x, y, m, n){    return (x >= 0 && x < m &&            y >= 0 && y < n);} // Function to calculate probability// that after N moves from a given// position (x, y) in m x n matrix,// boundaries of the matrix will not be crossed.function findProbability( m, n, x,                       y, N){    // boundary crossed    if (!isSafe(x, y, m, n))        return 0.0;     // N steps taken    if (N == 0)        return 1.0;     // Initialize result    let prob = 0.0;     // move up    prob += findProbability(m, n, x - 1,                            y, N - 1) * 0.25;     // move right    prob += findProbability(m, n, x,                            y + 1, N - 1) * 0.25;     // move down    prob += findProbability(m, n, x + 1,                            y, N - 1) * 0.25;     // move left    prob += findProbability(m, n, x,                            y - 1, N - 1) * 0.25;     return prob;} // Driver code// matrix sizelet m = 5, n = 5;// coordinates of starting pointlet i = 1, j = 1;// Number of stepslet N = 2;document.write( "Probability is "        +findProbability(m, n, i, j, N)); </script>
Output :  
Probability is 0.875
 
YouTubeGeeksforGeeks500K subscribersA matrix probability question | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:36•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=1VbNIBsrPCM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
KRV
nitin mittal
PranchalKatiyar
rohitsingh07052
Graph
Matrix
Matrix
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Topological Sorting
Detect Cycle in a Directed Graph
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Detect cycle in an undirected graph
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2