首页 > 解决方案 > 当向量的值已经在上面定义的函数中被 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 << " ";

它没有输出。 有人可以帮我解决这个问题吗?

标签: c++data-structuresc++14recursive-datastructuresdebug-backtrace

解决方案


推荐阅读