Untitled
unknown
plain_text
3 years ago
1.9 kB
8
Indexable
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
bool isCurrentCellSafe(int x, int y, int n, vector<vector<int> > &maze){
return !(x < 0 || y < 0 || x >=n || y>=n || maze[x][y] == 0);
}
void countUniqueHelper(vector<vector<int> > &maze, int x, int y, pair<int, int> &dest,
vector<vector<bool> > &visited, int &count){
if(x == dest.first && y == dest.second){
count++;
return;
}
visited[x][y] = 1;
int n = maze.size();
if(isCurrentCellSafe(x, y, n, maze)){
// 1. kya visited of x+1 is not 1
if(x + 1 < n && !visited[x+1][y]) {
countUniqueHelper(maze, x+1, y, dest, visited, count);
}
if(x - 1 >= 0 && !visited[x-1][y]) countUniqueHelper(maze, x-1, y, dest, visited, count);
if(y + 1 < n && !visited[x][y+1]) countUniqueHelper(maze, x, y+1, dest, visited, count);
if(y - 1 >= 0 && !visited[x][y-1]) countUniqueHelper(maze, x, y-1, dest, visited, count);
}
visited[x][y] = 0;
}
int countUniquePaths(vector<vector<int> > &maze, pair<int, int> &source, pair<int, int> &dest){
// conditions for the source cell
// 1. you can't go beyond the maze - i<0 , i>r, j<0, j>c
// 2. you can't go blocked cell - if maze[i][j] == 0
// 3. you can't revisit a cell - visited matrix
int n = maze.size(); // number of rows
int count = 0;
vector<vector<bool> > visited;
visited.resize(n, vector<bool>(n)); // false
int currX = source.first;
int currY = source.second;
countUniqueHelper(maze, currX, currY, dest, visited, count);
return count;
}
int main() {
vector<vector<int> > maze =
{
{1, 1, 1, 1},
{1, 1, 0, 1},
{0, 1, 0, 1},
{1, 1, 1, 1}
};
// pairs
pair<int, int> source = make_pair(0, 0);
pair<int, int> dest = make_pair(3, 3);
int uniquePaths = countUniquePaths(maze, source, dest);
cout << uniquePaths << endl;
return 0;
}Editor is loading...