[英]Number of paths in matrix
我的任务是编写一个 function,它返回矩阵中从左上角到右下角的有效路径数。 该矩阵由布尔值组成,其中 1 表示墙,0 表示空闲单元格。 所以任务是找到通过空闲单元格的路径数。 我写了一些代码,但不知何故不起作用。 我是编程初学者。 我必须使用递归并使用 use.at() 而不是 []。
#include "valid_path.h"
#include <vector>
void path_counter (unsigned int n, unsigned int m, unsigned int i,
unsigned int j, int &num, std::vector<std::vector<bool>> mat);
// PRE: -
// POST: Returns the number of valid paths through mat starting at (0, 0).
// Valid paths can only move right or down.
int valid_paths (const std::vector<std::vector<bool>> &mat) {
const unsigned int n = mat.size();
const unsigned int m = mat.at(0).size();
int num_of_paths = 0;
int i = 0;
int j = 0;
path_counter(n, m, i, j, num_of_paths, mat);
return num_of_paths;
}
void path_counter (unsigned int n, unsigned int m, unsigned int i,
unsigned int j, int &num, std::vector<std::vector<bool>> mat) {
if(i>n-1) {num+=0; }
while (i<=n-1 && j<=m-1) {
if ((i==n-2 && j==m-1) || (i==n-1 && j==m-2)) {
if (mat.at(i).at(j) == 0) {num+=1; }
}
else if (mat.at(i+1).at(j) == 0 && mat.at(i).at(j+1) == 0) {
path_counter(n, m, i+1, j, num, mat);
path_counter(n, m, i, j+1, num, mat);
}
else if (mat.at(i+1).at(j) == 1 && mat.at(i).at(j+1) == 0) {
path_counter(n, m, i, j+1, num, mat);
}
else if (mat.at(i+1).at(j) == 0 && mat.at(i).at(j+1) == 1) {
path_counter(n, m, i+1, j, num, mat);
}
else if (mat.at(i+1).at(j) == 1 && mat.at(i).at(j+1) == 1) {
num+=0;
}
}
}
我会放弃递归,只是将路径长度累加到与counts
大小相同的mat
中:
int getCount(const std::vector<std::vector<int>>& counts, int i, int j) {
if (i < 0) {
return 0;
}
if (j < 0) {
return 0;
}
return counts[i][j];
}
int valid_paths(const std::vector<std::vector<bool>> &mat) {
int m = mat.size();
int n = mat[0].size();
std::vector<std::vector<int>> counts;
// Initialization
for (const auto& row: mat) {
counts.push_back(std::vector<int>(row.size(), 0));
}
if (mat[0][0]) {
counts[0][0] = 1;
}
int k = (m-1) + (n-1) + 1;
for (int i = 1; i < k; i++) {
int row = std::min(i, m-1);
int col = i - row;
while (row >= 0 && col < n) {
counts[row][col] = mat[row][col]?
getCount(counts, row-1, col) + getCount(counts, row, col-1) : 0;
row--;
col++;
}
}
return counts[m-1][n-1];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.