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 () cells.i.e The shape of prison was () 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
() while the exit of the cell ().
note:->Alfie can move in all four direction{ if his current location is (), he can move to either
(), (), (), () }. If the first cell () and the last cell() 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 directionsint dx[] = {-1, 1, 0, 0};int dy[] = {0, 0, -1, 1};int ans, n;void dfs(int i, int j){//mark as visitedvis[i][j] = 1;//if we reach to the destinationif (i == n && j == n)ans++;for (int z = 0; z < 4; z++){int x = i + dx[z], y = j + dy[z];//check for valid cellif (x >= 1 && x <= n and y >= 1 && y <= n){//if not visited and value is 0//then call for dfsif (!a[x][y] and !vis[x][y])dfs(x, y);}}//mark as unvisited (backtrack)vis[i][j] = 0;}int main(){ans = 0;n = 4;vector<vector<int>> arr = {{0, 1, 1, 0},{0, 0, 1, 0},{0, 0, 0, 0},{0, 1, 1, 0}};for (int i = 1; i <= n; i++){for (int j = 1; j <= n; j++){a[i][j] = arr[i - 1][j - 1];}}dfs(1, 1);cout << ans << "\n";return 0;}
No comments:
Post a Comment