Prison Break

Alfie was a prisoner in mythland. Though Alfie was a witty and intelligent guy.He was confident of escaping prison.After few days of observation,He figured out that the prison consists of (N×N) cells.i.e The shape of prison was (N×N) matrix. Few of the cells of the prison contained motion detectors.So Alfie planned that while escaping the prison he will avoid those cells containing motion detectors.Yet before executing his plan,Alfie wants to know the total number of unique possible paths which he can take to escape the prison.Initially Alfie is in cell
(1,1) while the exit of the cell (N,N).

note:->Alfie can move in all four direction{ if his current location is (X,Y), he can move to either
(X+1,Y)(X1,Y)(X,Y+1)(X,Y1) }. If the first cell (1,1) and the last cell(N,N) contain motion detectors,then Alfie can't break out of the prison.

Example:

Input:  n = 4, arr = {{0, 1, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}, {0, 1, 1, 0}}
Output: 2

Approach

C++

#include <bits/stdc++.h>
using namespace std;

const int N = 22;

int a[N][N];

bool vis[N][N];

//all four directions
int dx[] = {-1100};
int dy[] = {00, -11};
int ansn;

void dfs(int iint j)
{

    //mark as visited
    vis[i][j] = 1;

    //if we reach to the destination
    if (i == n && j == n)
        ans++;

    for (int z = 0z < 4z++)
    {
        int x = i + dx[z], y = j + dy[z];

        //check for valid cell
        if (x >= 1 && x <= n and y >= 1 && y <= n)
        {

            //if not visited and value is 0
            //then call for dfs
            if (!a[x][y] and !vis[x][y])
                dfs(xy);
        }
    }

    //mark as unvisited (backtrack)
    vis[i][j] = 0;
}

int main()
{

    ans = 0;

    n = 4;
    vector<vector<int>> arr = {{0110},
                               {0010},
                               {0000},
                               {0110}};

    for (int i = 1i <= ni++)
    {
        for (int j = 1j <= nj++)
        {
            a[i][j] = arr[i - 1][j - 1];
        }
    }
    dfs(11);

    cout << ans << "\n";

    return 0;
}


No comments:

Post a Comment