📜  计算遍历矩阵的方式数量

📅  最后修改于: 2021-05-04 22:04:19             🧑  作者: Mango

给定一个二维矩阵,某人如何以这种方式从左上角遍历到右下角?
条件-在任何特定的单元格上,可能的移动是向下还是向右,没有其他可能的步骤。
到达终点时停止。

例子:

Input : 3 3
Output : 6

Input : 5 5
Output : 70

如果仔细观察,我们会发现到达一个单元格的方式数=它可以到达其上方单元格的方式数+它可以到达其左侧单元格的方式数。

因此,根据它开始填充2D数组,并在完全填充数组后返回最后一个单元格。

下面是上述方法的实现:

C++
// C++ program using recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
#include 
using namespace std;
 
// Returns The number of way from top-left
// to mat[m-1][n-1]
int countPaths(int m, int n)
{
    // Return 1 if it is the first row or
    // first column
    if (m == 1 || n == 1)
        return 1;
  
    // Recursively find the no of way to
    // reach the last cell.
    return countPaths(m - 1, n) +
           countPaths(m, n - 1);
}
 
// Driver code
int main()
{
    int n = 5;
    int m = 5;
    cout << countPaths(n, m);
    return 0;
}


Java
// Java program using recursive
// solution to count number of
// ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
import java.lang.*;
import java.util.*;
 
class GFG
{
// Returns The number of way
// from top-left to mat[m-1][n-1]
public int countPaths(int m, int n)
{
    // Return 1 if it is the first
    // row or first column
    if (m == 1 || n == 1)
        return 1;
 
    // Recursively find the no of
    // way to reach the last cell.
    return countPaths(m - 1, n) +
           countPaths(m, n - 1);
}
 
// Driver Code
public static void main(String args[])
{
    GFG g = new GFG();
 
    int n = 5, m = 5;
    System.out.println(g.countPaths(n, m));
}
}
 
// This code is contributed
// by Akanksha Rai(Abby_akku)


Python3
# Python3 program using recursive solution to count
# number of ways to reach mat[m-1][n-1] from
# mat[0][0] in a matrix mat[][]
 
# Returns The number of way from top-left
# to mat[m-1][n-1]
def countPaths(m, n) :
 
    # Return 1 if it is the first row or
    # first column
    if m == 1 or n == 1 :
        return 1
 
    # Recursively find the no of way to
    # reach the last cell.
    return (countPaths(m - 1, n) +
            countPaths(m, n - 1))
 
 
# Driver code    
if __name__ == "__main__" :
 
    n = 5
    m = 5
    print(countPaths(n, m))
 
# This code is contributed by ANKITRAI1


C#
// C# program using recursive
// solution to count number of
// ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
using System;
 
class GFG
{
// Returns The number of way
// from top-left to mat[m-1][n-1]
public int countPaths(int m, int n)
{
    // Return 1 if it is the first
    // row or first column
    if (m == 1 || n == 1)
        return 1;
 
    // Recursively find the no of
    // way to reach the last cell.
    return countPaths(m - 1, n) +
        countPaths(m, n - 1);
}
 
// Driver Code
public static void Main()
{
    GFG g = new GFG();
 
    int n = 5, m = 5;
    Console.WriteLine(g.countPaths(n, m));
    Console.Read();
}
}
 
// This code is contributed
// by SoumikMondal


PHP


C++
// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
#include 
using namespace std;
 
// Returns The number of way from top-left
// to mat[m-1][n-1]
int countPaths(int m, int n)
{
    int dp[m+1][n+1];
     
    for (int i=1; i<=m; i++)
    {
        for (int j=1; j<=n; j++)
        {
           if (i==1 || j == 1)
              dp[i][j] = 1;
            else
              dp[i][j] = dp[i-1][j] + dp[i][j-1];             
        }
    }
   
    return dp[m][n];
}
 
// Driver code
int main()
{
    int n = 5;
    int m = 5;
    cout << countPaths(n, m);
    return 0;
}


Java
// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
 
class GFG
{
    // Returns The number of way from top-left
    // to mat[m-1][n-1]
    static int countPaths(int m, int n)
    {
        int [][]dp=new int[m+1][n+1];
         
        for (int i=1; i<=m; i++)
        {
            for (int j=1; j<=n; j++)
            {
            if (i==1 || j == 1)
                dp[i][j] = 1;
                else
                dp[i][j] = dp[i-1][j] + dp[i][j-1];            
            }
        }
     
        return dp[m][n];
    }
     
    // Driver code
    public static void main(String []args)
    {
        int n = 5;
        int m = 5;
        System.out.println(countPaths(n, m));
         
    }
}
 
// This code is contributed
// by ihritik (Hritik Raj)


Python3
# A simple recursive solution to
# count number of ways to reach
# mat[m-1][n-1] from mat[0][0]
# in a matrix mat[][]
 
# Returns The number of way
# from top-left to mat[m-1][n-1]
def countPaths(m, n):
 
    dp = [[0 for i in range(m + 1)]
             for j in range(n + 1)]
     
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if (i == 1 or j == 1):
                dp[i][j] = 1
            else:
                dp[i][j] = (dp[i - 1][j] +
                            dp[i][j - 1])            
     
    return dp[m][n]
 
# Driver code
if __name__ =="__main__":
     
    n = 5
    m = 5
    print(countPaths(n, m))
 
# This code is contributed
# by ChitraNayal


C#
// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
 
using System;
class GFG
{
    // Returns The number of way from top-left
    // to mat[m-1][n-1]
    static int countPaths(int m, int n)
    {
        int [,]dp=new int[m+1,n+1];
         
        for (int i=1; i<=m; i++)
        {
            for (int j=1; j<=n; j++)
            {
            if (i==1 || j == 1)
                dp[i,j] = 1;
                else
                dp[i,j] = dp[i-1,j] + dp[i,j-1];            
            }
        }
     
        return dp[m,n];
    }
     
    // Driver code
    public static void Main()
    {
        int n = 5;
        int m = 5;
        Console.WriteLine(countPaths(n, m));
         
    }
}
 
// This code is contributed
// by ihritik (Hritik Raj)


PHP


C++
// C++ program for above approach
#include
using namespace std;
 
// Find factorial
int factorial(int n)
{
    int res = 1, i;
     
    for(i = 2; i <= n; i++)
        res *= i;
         
    return res;
}
 
// Find number of ways to reach
// mat[m-1][n-1] from mat[0][0]
// in a matrix mat[][]]
 int countWays(int m, int n)
{
    m = m - 1;
    n = n - 1;
     
    return factorial(m + n) /
          (factorial(m) *
           factorial(n));
}
 
// Driver Code
int main()
{
    int m = 5;
    int n = 5;
    
    // Function call
    int result = countWays(m, n);
     
    cout << result;
}
 
// This code is contributed by chahattekwani71


Java
// Java Program for above approach
import java.io.*;
 
class GFG {
 
    // Find factorial
    static int factorial(int n)
    {
        int res = 1, i;
        for (i = 2; i <= n; i++)
            res *= i;
        return res;
    }
    // Find number of ways to reach
    // mat[m-1][n-1] from mat[0][0]
    // in a matrix mat[][]]
    static int countWays(int m, int n)
    {
        m = m - 1;
        n = n - 1;
        return factorial(m + n)
            / (factorial(m) * factorial(n));
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int m = 5;
        int n = 5;
       
        // Function Call
        int result = countWays(m, n);
        System.out.println(result);
    }
}


Python3
# Python3 program for
# the above approach
 
# Find factorial
def factorial(n):
 
    res = 1
     
    for i in range(2, n + 1):
        res *= i
         
    return res
 
# Find number of ways to reach
# mat[m-1][n-1] from mat[0][0]
# in a matrix mat[][]]
def countWays(m, n):
 
    m = m - 1
    n = n - 1   
    return (factorial(m + n) //
           (factorial(m) *
            factorial(n)))
 
# Driver code  
m = 5
n = 5
 
# Function call
result = countWays(m, n)
 
print(result)
 
# This code is contributed by divyeshrabadiya07


C#
// C# Program for above approach
using System;
 
class GFG{
     
// Find factorial
static int factorial(int n)
{
    int res = 1, i;
    for(i = 2; i <= n; i++)
        res *= i;
         
    return res;
}
 
// Find number of ways to reach
// mat[m-1][n-1] from mat[0][0]
// in a matrix mat[][]]
static int countWays(int m, int n)
{
    m = m - 1;
    n = n - 1;
     
    return factorial(m + n) /
          (factorial(m) * factorial(n));
}
 
// Driver code
static void Main()
{
    int m = 5;
    int n = 5;
    
    // Function Call
    int result = countWays(m, n);
     
    Console.WriteLine(result);
}
}
 
// This code is contributed by divyesh072019


输出
70

上述解决方案具有指数时间复杂度。可以使用动态编程对其进行优化,因为存在重叠的子问题(下面在部分递归树中针对m = 3,n = 3突出显示)

CP(3, 3)
          /        \
     CP(2, 3)     CP(3, 2)
     /    \        /     \
 CP(1,3) CP(2,2) CP(2,2) CP(3,1)

C++

// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
#include 
using namespace std;
 
// Returns The number of way from top-left
// to mat[m-1][n-1]
int countPaths(int m, int n)
{
    int dp[m+1][n+1];
     
    for (int i=1; i<=m; i++)
    {
        for (int j=1; j<=n; j++)
        {
           if (i==1 || j == 1)
              dp[i][j] = 1;
            else
              dp[i][j] = dp[i-1][j] + dp[i][j-1];             
        }
    }
   
    return dp[m][n];
}
 
// Driver code
int main()
{
    int n = 5;
    int m = 5;
    cout << countPaths(n, m);
    return 0;
}

Java

// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
 
class GFG
{
    // Returns The number of way from top-left
    // to mat[m-1][n-1]
    static int countPaths(int m, int n)
    {
        int [][]dp=new int[m+1][n+1];
         
        for (int i=1; i<=m; i++)
        {
            for (int j=1; j<=n; j++)
            {
            if (i==1 || j == 1)
                dp[i][j] = 1;
                else
                dp[i][j] = dp[i-1][j] + dp[i][j-1];            
            }
        }
     
        return dp[m][n];
    }
     
    // Driver code
    public static void main(String []args)
    {
        int n = 5;
        int m = 5;
        System.out.println(countPaths(n, m));
         
    }
}
 
// This code is contributed
// by ihritik (Hritik Raj)

Python3

# A simple recursive solution to
# count number of ways to reach
# mat[m-1][n-1] from mat[0][0]
# in a matrix mat[][]
 
# Returns The number of way
# from top-left to mat[m-1][n-1]
def countPaths(m, n):
 
    dp = [[0 for i in range(m + 1)]
             for j in range(n + 1)]
     
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if (i == 1 or j == 1):
                dp[i][j] = 1
            else:
                dp[i][j] = (dp[i - 1][j] +
                            dp[i][j - 1])            
     
    return dp[m][n]
 
# Driver code
if __name__ =="__main__":
     
    n = 5
    m = 5
    print(countPaths(n, m))
 
# This code is contributed
# by ChitraNayal

C#

// A simple recursive solution to count
// number of ways to reach mat[m-1][n-1] from
// mat[0][0] in a matrix mat[][]
 
using System;
class GFG
{
    // Returns The number of way from top-left
    // to mat[m-1][n-1]
    static int countPaths(int m, int n)
    {
        int [,]dp=new int[m+1,n+1];
         
        for (int i=1; i<=m; i++)
        {
            for (int j=1; j<=n; j++)
            {
            if (i==1 || j == 1)
                dp[i,j] = 1;
                else
                dp[i,j] = dp[i-1,j] + dp[i,j-1];            
            }
        }
     
        return dp[m,n];
    }
     
    // Driver code
    public static void Main()
    {
        int n = 5;
        int m = 5;
        Console.WriteLine(countPaths(n, m));
         
    }
}
 
// This code is contributed
// by ihritik (Hritik Raj)

的PHP


输出
70

时间复杂度: O(m * n)

另一种方法(有效):

有一种更有效的方法可以解决O(m)或O(n)中的较大者。

我们可以对正确的操作和向下的操作进行排列。

假设列数为m,行数为n,则排列数=(m + n)!/(m!* n!)

以下是上述逻辑的实现。

C++

// C++ program for above approach
#include
using namespace std;
 
// Find factorial
int factorial(int n)
{
    int res = 1, i;
     
    for(i = 2; i <= n; i++)
        res *= i;
         
    return res;
}
 
// Find number of ways to reach
// mat[m-1][n-1] from mat[0][0]
// in a matrix mat[][]]
 int countWays(int m, int n)
{
    m = m - 1;
    n = n - 1;
     
    return factorial(m + n) /
          (factorial(m) *
           factorial(n));
}
 
// Driver Code
int main()
{
    int m = 5;
    int n = 5;
    
    // Function call
    int result = countWays(m, n);
     
    cout << result;
}
 
// This code is contributed by chahattekwani71

Java

// Java Program for above approach
import java.io.*;
 
class GFG {
 
    // Find factorial
    static int factorial(int n)
    {
        int res = 1, i;
        for (i = 2; i <= n; i++)
            res *= i;
        return res;
    }
    // Find number of ways to reach
    // mat[m-1][n-1] from mat[0][0]
    // in a matrix mat[][]]
    static int countWays(int m, int n)
    {
        m = m - 1;
        n = n - 1;
        return factorial(m + n)
            / (factorial(m) * factorial(n));
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int m = 5;
        int n = 5;
       
        // Function Call
        int result = countWays(m, n);
        System.out.println(result);
    }
}

Python3

# Python3 program for
# the above approach
 
# Find factorial
def factorial(n):
 
    res = 1
     
    for i in range(2, n + 1):
        res *= i
         
    return res
 
# Find number of ways to reach
# mat[m-1][n-1] from mat[0][0]
# in a matrix mat[][]]
def countWays(m, n):
 
    m = m - 1
    n = n - 1   
    return (factorial(m + n) //
           (factorial(m) *
            factorial(n)))
 
# Driver code  
m = 5
n = 5
 
# Function call
result = countWays(m, n)
 
print(result)
 
# This code is contributed by divyeshrabadiya07

C#

// C# Program for above approach
using System;
 
class GFG{
     
// Find factorial
static int factorial(int n)
{
    int res = 1, i;
    for(i = 2; i <= n; i++)
        res *= i;
         
    return res;
}
 
// Find number of ways to reach
// mat[m-1][n-1] from mat[0][0]
// in a matrix mat[][]]
static int countWays(int m, int n)
{
    m = m - 1;
    n = n - 1;
     
    return factorial(m + n) /
          (factorial(m) * factorial(n));
}
 
// Driver code
static void Main()
{
    int m = 5;
    int n = 5;
    
    // Function Call
    int result = countWays(m, n);
     
    Console.WriteLine(result);
}
}
 
// This code is contributed by divyesh072019
输出
70

时间复杂度: O(n)