📌  相关文章
📜  在允许进行四步移动的矩阵中打印从左上到右下的所有路径

📅  最后修改于: 2021-04-29 02:33:05             🧑  作者: Mango

问题是要打印从mXn矩阵的左上角到右下角的所有可能路径,并带有从每个单元格可以向上,向右,向左或向下移动的约束条件。

例子:

Input :  
1 2 3 
4 5 6 
Output :  
1 2 3 6 
1 2 5 6  
1 4 5 6  
4 5 2 3 6 

Input :
1 2 3
4 5 6
7 8 9
Output :
1 2 3 6 9 
1 2 3 6 5 8 9 
1 2 3 6 5 4 7 8 9 
1 2 5 6 9 
1 2 5 8 9 
1 2 5 4 7 8 9 
1 4 5 6 9 
1 4 5 8 9 
1 4 5 2 3 6 9 
1 4 7 8 9 

此问题主要是对矩阵中从左上到右下的所有路径进行计数的扩展,允许进行两次移动

该算法是一种简单的递归算法,从每个单元格开始,先向下打印所有路径,然后向右打印所有路径,然后向上打印所有路径,然后向左打印所有路径。对遇到的每个单元递归执行此操作。此处我们将使用哈希矩阵,因为它不会重复已经遍历的相同路径。

以下是上述算法的C++实现。

// Print All path from top left to bottom right
#include 
#include 
using namespace std;
  
// Function to print all path
void printAllPath(vector > vec, 
                  vector > hash,
          int i, int j, vector res = {})
{
    // check Condition
    if (i < 0 || j < 0 || i >= vec.size() || 
       j >= vec[0].size() || hash[i][j] == 1)
        return;
  
    // once it get the position (bottom right) 
    // than print the path
    if (i == vec.size() - 1 && j == vec[0].size() - 1) {
  
        // push the last element
        res.push_back(vec[i][j]);
        int k;
  
        // print the path
        for (k = 0; k < res.size(); k++)
            cout << res[k] << " ";
  
        cout << "\n";
  
        return;
    }
  
    // if the path is traverse already then
    // it will not go again the same path
    hash[i][j] = 1;
  
    // store the path
    res.push_back(vec[i][j]);
  
    // go to the right
    printAllPath(vec, hash, i, j + 1, res);
  
    // go to the down
    printAllPath(vec, hash, i + 1, j, res);
  
    // go to the up
    printAllPath(vec, hash, i - 1, j, res);
  
    // go to the left
    printAllPath(vec, hash, i, j - 1, res);
  
    // pop the last element
    res.pop_back();
  
    // hash position 0 for traverse another path
    hash[i][j] = 0;
}
  
// Driver code
int main()
{
    // Given matrix
    vector > vec = { { 1, 2, 3 },
                                 { 4, 5, 6 } };
  
    // mxn(2x3) 2d hash matrix
    vector > hash(2, vector(3, 0));
  
    // print All Path of matrix
    printAllPath(vec, hash, 0, 0);
  
    return 0;
}
输出:
1 2 3 6 
1 2 5 6 
1 4 5 6 
1 4 5 2 3 6