【发布时间】:2020-03-11 19:22:26
【问题描述】:
我有一个20x30 矩阵,其中填充了随机数[ 0, 1, 2 ]。我需要找到一条仅由 1 组成的路径,该路径从左上角开始,到右下角结束。我需要帮助找到 1 的路径。另外,如何打印我踩过的每个数字的坐标?我可以显示我踩过的数字,但我在显示它的坐标时遇到了问题。
这是我当前的代码
#include <iostream>
#include <vector>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
const int N = 3;
const int M = 3;
void mtxFeltolt(int (&mat)[N][M]);
void mtxPrint(int (&mat)[N][M]);
void printPaths(int mat[M][N], vector<int> &route, int i, int j)
{
// if last cell is reached
if (i == M - 1 && j == N - 1)
{
// print the current route
for (int i: route) {
cout << i << " - ";
}
cout << mat[i][j] << endl;
return;
}
// include current cell in route
route.push_back(mat[i][j]);
// move right
if (j + 1 < N){
printPaths(mat, route, i, j + 1);
}
// move down
if (i + 1 < M){
printPaths(mat, route, i + 1, j);
}
// move diagonally
if (i + 1 < M && j + 1 < N){
printPaths(mat, route, i + 1, j + 1);
}
// backtrack
route.pop_back();
}
// Print all shortest routes in a rectangular grid
void printPaths(int mat[][N])
{
// vector to store current route
vector<int> route;
// start from the first cell (0, 0)
printPaths(mat, route, 0, 0);
}
// main function
int main()
{
int mat[N][M];
srand (time(NULL));
mtxFeltolt(mat);
cout << "A matrix: " <<endl;
mtxPrint(mat);
cout << endl;
cout << "---- A megfelelo utak ----" << endl;
printPaths(mat);
return 0;
}
void mtxFeltolt(int (&mat)[N][M]){
for(int i=0; i < N; i++){
for(int j=0; j < M; j++)
mat[i][j] = rand() % 3;
}
}
void mtxPrint(int (&mat)[N][M]){
for(int i=0; i < N; i++){
for(int j = 0; j < M; j++){
cout << mat[i][j] << " ";
}
cout << endl;
}
}
【问题讨论】:
-
欢迎来到 StackOverflow。我不确定您在这里要做什么,或者您为什么使用
rcpp标签——您的问题与 Rcpp 无关,所以我现在删除了标签。如果你需要一些友好的、有据可查的矩阵 C++ 类的帮助,可以考虑 arma.sf.net 的犰狳。祝你好运! -
一个观察结果是
route是一个整数向量。如果路径存在,它将全为 1,这不是很有用。我认为您的意思是存储坐标而不是值。您可以使用std::vector<std::pair<int, int>> route并存储{i, j}这将是坐标。 -
商店 {i,j} 是什么意思,您可以编辑我的代码并粘贴到那里吗?非常感谢
-
std::pair是一个包含两种类型的容器。它非常适合二维坐标。如果您将route声明为std::vector<std::pair<int, int>>,然后执行route.push_back({i, j});,则路径向量将包含所有坐标。 -
对不起,我还是不明白,我是这种语言的新手,但无论如何都需要帮助
标签: c++