【发布时间】:2018-10-09 10:09:42
【问题描述】:
我在这里发表了类似的帖子,但没有得到任何反馈。问题来自here。
我试图简单地打印出最长递增矩阵的条目。当我尝试以下矩阵时,我以为我已经弄清楚了:
2 2 1
1 2 1
2 2 1
我得到了一个输出:
1
2
然后当我增加 n 时,m = 4。我得到了这个矩阵:
2 2 1 1
2 1 2 2
1 2 2 3
1 2 1 3
路径条目的输出如下:
1
1
2
什么时候应该是:
1
2
3
这是我的代码:
#include <algorithm>
#include <cmath>
#include <list>
#include <vector>
#include <stdio.h>
#include <random>
#include <utility>
#include <iostream>
void printPath(std::vector<int> &numPaths) {
std::sort(numPaths.begin(), numPaths.end());
for(int i = 0; i < numPaths.size(); i++) {
std::cout << numPaths[i] << std::endl;
}
}
int DFS(int i, int j, const std::vector<std::vector<int> > &matrix, std::vector<std::vector<int> > &length) {
std::vector<std::pair<int,int> > dics{{-1,0},{1,0},{0,-1},{0,1}}; // used to check the directions left, right, up, down
std::vector<int> path;
if(length[i][j] == -1) {
int len = 0;
for(auto p: dics) {
int x = i + p.first, y = j + p.second;
if(x < 0 || x >= matrix.size() || y < 0 || y >= matrix[0].size()) continue; // Check to make sure index is not out of boundary
if(matrix[x][y] > matrix[i][j]) { // compare number
len = std::max(len, DFS(x,y,matrix,length));
}
}
length[i][j] = len + 1;
}
return length[i][j];
}
int longestPath(std::vector<std::vector<int> > matrix) {
int n = matrix[0].size();
if (n == 0) {
return 0;
}
int m = matrix.size();
if (m == 0) {
return 0;
}
std::vector<std::vector<int> > length(m, std::vector<int>(n,-1));
std::vector<int> numPaths;
int len = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int newLen = DFS(i,j,matrix,length);
if(newLen > len) {
numPaths.push_back(matrix[i][j]);
}
len = std::max(len, DFS(i, j, matrix, length));
}
}
printPath(numPaths);
return len;
}
int main() {
// Specify the number of rows and columns of the matrix
int n = 4;
int m = 4;
// Declare random number generator
std::mt19937 gen(10);
std::uniform_int_distribution<> dis(1, 3);
// Fill matrix
std::vector<std::vector<int> > matrix;
for(int i = 0; i < m; i++) {
std::vector<int> row;
for(int j = 0; j < n; j++) {
row.push_back(0);
}
matrix.push_back(row);
}
// Apply random number generator to create matrix
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
matrix[i][j] = dis(gen);
}
}
// Print matrix to see contents
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
//std::vector<std::vector<int> > mat = {{1,2,3}};
int result = longestPath(matrix);
std::cout << "The longest path is " << result << std::endl;
}
如果有人能告诉我哪里出错了,我将不胜感激。
【问题讨论】:
-
这不是免费的调试服务,我们希望您展示您使用调试器或其他更简单的方法(例如调试打印语句)调试代码的尝试。这不会是您唯一一次在代码中遇到错误,学习调试程序对您的帮助远大于让别人为您找到错误。 idownvotedbecau.se/nodebugging
-
@FeiXiang 谢谢飞,在调试方面我还需要更多的练习。你有什么建议可以让我更好地学习调试吗?
-
@Snarfy How to debug small programs 有一些不错的建议。
-
除了提到的站点烧杯之外,我的第一条评论末尾的链接中还有一些关于如何使用不同调试器的信息。 good book 应该教你如何尽早调试。
标签: c++ algorithm matrix dynamic-programming depth-first-search