0

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 ?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • [Works for me](https://godbolt.org/z/879dxGWf6) exactly as written – Igor Tandetnik Sep 25 '21 at 02:00
  • Normal compiler shows segmentation error. But I got the fault, it was in the isSafe loop, it went out of loop to the array. In the first loop it is checked for 0,0 and array looks in direction off i=-1 and even j=-1. So that was the bug – Pranay Dey Sep 25 '21 at 16:21

0 Answers0