c++ - 当向量的值已经在上面定义的函数中被 push_backed 时,向量的值不能在 main() 中产生的回溯问题
问题描述
迷宫里的老鼠
老鼠需要移动的方向
#include <bits/stdc++.h>
#include <vector>
using namespace std;
bool isSafe(vector<vector<int>> &m, int i, int j, int n)
{
if (i < n && j < n && m[i][j] == 1)
return true;
return false;
}
int RIM(vector<vector<int>> &m, int i, int j, int n, string out, vector<string> &ans)
{
if (i == n - 1 && j == n - 1)
{
ans.push_back(out);
return 0;
}
if (isSafe(m, i, j, n))
{
m[i][j] = 2;
//cout<< m[i][j]<<" "<< out<<endl;
out.push_back('D');
RIM(m, i + 1, j, n, out, ans);
out.pop_back();
out.push_back('R');
RIM(m, i, j + 1, n, out, ans);
out.pop_back();
out.push_back('U');
RIM(m, i - 1, j, n, out, ans);
out.pop_back();
out.push_back('L');
RIM(m, i, j - 1, n, out, ans);
out.pop_back();
m[i][j] = 1;
return 0;
}
return 0;
}
int main()
{
vector<string> ans;
vector<vector<int>> m{
{1, 0, 0, 0}, {1, 1, 0, 1}, {1, 1, 0, 0}, {0, 1, 1, 1}};
RIM(m, 0, 0, m.size(), "", ans);
for (auto i : ans)
cout << i << " ";
return 0;
}
输入和输出:
Input:
1 0 0 0
1 1 0 1
1 1 0 0
0 1 1 1
Output:
DDRDRR DRDDRR
但问题是它没有采用我尝试在 main() 中打印的推回向量 ans。我什至尝试在全局所有函数之外声明字符串向量,但即便如此它也没有打印它拥有的新分配值。
int RIM(vector<vector<int>> &m, int i, int j, int n, string out, vector<string> &ans)
{
if (i == n - 1 && j == n - 1)
{
ans.push_back(out);
return 0;
}
在 main() 内部:
RIM(m, 0, 0, m.size(), "", ans);
for (auto i : ans)
cout << i << " ";
它没有输出。 有人可以帮我解决这个问题吗?
解决方案
推荐阅读
- reactjs - 在材料 ui 反应模板上更改主题
- pivot - 如何删除一些旧的枢轴标签附近或最近的结果相似?
- sql - 我想从蜂巢的多列中找到最高行
- javascript - Node、Express 和 MongoDB 中的 HTML 注入。(EJS 模板引擎)
- android - 将手机旋转到横向位置后,如何在 onSaveInstanceState() 中保存文本视图颜色?
- github - How to Change Repository Information?
- python - 使用opencv检测水印
- python - 范围滑块更改 Django 中的函数参数
- c# - C# Windows 窗体仅在我的计算机上成功运行,我尝试更改框架版本
- java - EJB Websocket 握手错误:响应代码不是 101:404