提问者:小点点

C++代码不给出输出(主题:递归和二维向量)


  1. 您将得到一个数字n,表示行数。
  2. 您将得到一个数字m,表示列数。
  3. 给出了N*M个数字,表示2D数组A的元素。数字只能是1或0。
  4. 你站在左上角,必须到达右下角。只允许四个动作:'t'(1步向上),'l'(1步向左),'d'(1步向下),'r'(1步向右).只能移动到其中值为0的单元格。您不能移出边界或在其中值为1的单元格中(1表示障碍)
  5. 完成floodfill函数的主体--不更改签名--以打印可用于从左上角移动到右下角的所有路径。

这就是问题所在,这里是参考链接https://www.pepcoding.com/resources/online-Java-基金会/递归-回溯/洪水-填充-官方/OJQuestion#

我使用了下面的代码,检查了很多次,没有发现任何错误,请帮助我找出错误的地方,我是用C++编写的


#include <iostream>
#include <string>
#include <vector>

using namespace std;

void floodfill(vector<vector<int>> maze, int sr, int sc, string psf, vector<vector<int>> visited)
{
    if (sr < 0 || sc < 0 || sr == maze.size() || sc == maze[0].size() ||
        maze[sr][sc] == 1 || visited[sr][sc] == 1)
            return;
    if (sr == maze.size() - 1 && sc == maze[0].size() - 1)
    {
        cout << psf << endl;
        return;
    }
    visited[sr][sc] == 1;
    floodfill(maze, sr - 1, sc, psf + "t", visited);
    floodfill(maze, sr, sc - 1, psf + "l", visited);
    floodfill(maze, sr + 1, sc, psf + "d", visited);
    floodfill(maze, sr, sc + 1, psf + "r", visited);
    visited[sr][sc] == 0;
}

int main()
{
    int n, m;
    cin >> n >> m;
    vector<vector<int>> arr(n, vector<int>(m));
    vector<vector<int>> visited(n, vector<int>(m));
    for (int i = 0; i < n; i++)
        for (int j = 0; j < m; j++)
            cin >> arr[i][j];

    floodfill(arr, 0, 0, "", visited);
}

请有人来帮帮Thnx..


共1个答案

匿名用户

您需要添加对向量的引用。C和C++是按值传递语言,您需要显式地告诉C++您是按引用传递的。

void floodfill(vector<vector<int>>& maze, int sr, int sc, string psf, vector<vector<int>>& visited)
{
    if (sr < 0 || sc < 0 || sr == maze.size() || sc == maze[0].size() ||
        maze[sr][sc] == 1 || visited[sr][sc] == 1)
            return;
    if (sr == maze.size() - 1 && sc == maze[0].size() - 1)
    {
        cout << psf << endl;
        return;
    }
    visited[sr][sc] = 1;
    floodfill(maze, sr - 1, sc, psf + "t", visited);
    floodfill(maze, sr, sc - 1, psf + "l", visited);
    floodfill(maze, sr + 1, sc, psf + "d", visited);
    floodfill(maze, sr, sc + 1, psf + "r", visited);
    visited[sr][sc] = 0;
}

此外,我认为您可能希望在这里执行assignmnet访问[sr][sc]==1;

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|代码|给出|输出|主题|递归|二维|向量)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?