Backtracking problem where the vector's value cant be produced inside main() when it is already been push_backed in a function defined above

50 views Asked by At

Rat In The Maze

The direction the rat needs to move

#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;
}

The INPUT and OUTPUT:

Input:
1 0 0 0 
1 1 0 1
1 1 0 0
0 1 1 1

Output:
DDRDRR DRDDRR 

But the issue is it's not taking pushed back vector ans which I tried printing in the main(). I even tried declaring the string vector outside all the functions globally but even then it is not printing the new assigned value it has.

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;
    }

inside main() :

 RIM(m, 0, 0, m.size(), "", ans);
    for (auto i : ans)
        cout << i << " ";

It gives no output. Can any one please help me resolve this problem ?

0

There are 0 answers