使用 C++ 統計遍歷矩陣的方式數量
給定一個維度為行 X 列的二維矩陣。目標是統計從單元格 0,0 到單元格行,列遍歷矩陣的方式數量,只能使用向右和向下的移動,即第一步可以從 0,0 移動到 0,1(向下)或 1,0(向右),而不能移動到 1,1(對角線)。
例如
輸入
col = 2; row = 4
輸出
Count of number of ways to traverse a Matrix are: 4
解釋
我們可以從單元格 0,0 到達 2,4 的方式如下所示:
輸入
col = 4; row = 3
輸出
Count of number of ways to traverse a Matrix are: 10
解釋
We will reduce the problem into smaller recursions. Count ways for col=3, row=2, then for col=2, row=1 ….. For col=1 or row=1 the answer will be 1. (only right or only down move).
下面程式中使用的方案如下
在這種方案中,我們將使用遞迴方法。對於行或列為 1 的情況,只有一種方式,即 1 個向右的直線移動或 1 個向下的直線移動。這將是遞迴的終止條件。
獲取矩陣維度的整數行和列。
函式 ways_traverse_matrix(int row, int col) 獲取維度並返回遍歷矩陣的方式數量。
如果 row==1,則返回 1。
如果 col==1,則返回 1。
否則,使用遞迴計算方式 ways_traverse_matrix(temp_1, col) + ways_traverse_matrix(row, temp_2)。
這裡 temp_1=上一行號,temp_2=上一列號。
最後,我們將得到總方式的數量。
示例
#include <bits/stdc++.h> using namespace std; int ways_traverse_matrix(int row, int col){ if (row == 1){ return 1; } else if(col == 1){ return 1; } else { int temp_1 = row − 1; int temp_2 = col − 1; return ways_traverse_matrix(temp_1, col) + ways_traverse_matrix(row, temp_2); } } int main(){ int col = 2; int row = 2; cout<<"Count the number of ways to traverse a Matrix are: "<<ways_traverse_matrix(row, col); return 0; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
Count the number of ways to traverse a Matrix are: 2
廣告