Given a square maze containing positive numbers, find all paths from top left cell to the middle cell. We can move exactly
nsteps from a cell in 4 directions i.e. North, East, West and South wherenis value of the cell.
Here is my code, please help to find the bug. Not getting the output. I used the backtracking to get the output. I think its going for an infinite loop. Can't find the bug.
#include <bits/stdc++.
#define r 9
#define c 9
using namespace std;
bool is_valid(pair<int , int> pt , set<pair<int , int> > visited) {
return (pt.first >= 0 && pt.second >= 0 && pt.first < r && pt.second < c && visited.find(pt) == visited.end());
}
void print(vector<pair<int , int> > path) {
for (int i = 0 ; i < path.size() ; ++i)
cout<<"("<<path[i].first<<","<<path[i].second<<")->";
cout<<"END"<<endl;
}
void bar(int arr[][c] , vector<pair<int , int> > path , set<pair<int , int> > visited , int x , int y) {
if (x == r/2 && y == c/2) {
print(path);
return;
}
pair<int , int> pt;
pt = make_pair(x + arr[x][y] , y);
if (is_valid(pt , visited)) {
visited.insert(pt);
path.push_back(pt);
bar(arr , path , visited , pt.first , pt.second);
visited.erase(pt);
path.pop_back();
}
pt = make_pair(x - arr[x][y] , y);
if (is_valid(pt , visited)) {
visited.insert(pt);
path.push_back(pt);
bar(arr , path , visited , pt.first , pt.second);
visited.erase(pt);
path.pop_back();
}
pt = make_pair(x , y + arr[x][y]);
if (is_valid(pt , visited)) {
visited.insert(pt);
path.push_back(pt);
bar(arr , path , visited , pt.first , pt.second);
visited.erase(pt);
path.pop_back();
}
pt = make_pair(x , y - arr[x][y]);
if (is_valid(pt , visited)) {
visited.insert(pt);
path.push_back(pt);
bar(arr , path , visited , pt.first , pt.second);
visited.erase(pt);
path.pop_back();
}
}
void foo(int arr[][c]) {
set<pair<int , int> > visited;
vector<pair<int , int> > path;
int x = 0;
int y = 0;
visited.insert(make_pair(0 , 0));
path.push_back(make_pair(0 , 0));
bar(arr , path , visited , x , y);
}
int main() {
int maze[r][c] =
{
{ 3, 5, 4, 4, 7, 3, 4, 6, 3 },
{ 6, 7, 5, 6, 6, 2, 6, 6, 2 },
{ 3, 3, 4, 3, 2, 5, 4, 7, 2 },
{ 6, 5, 5, 1, 2, 3, 6, 5, 6 },
{ 3, 3, 4, 3, 0, 1, 4, 3, 4 },
{ 3, 5, 4, 3, 2, 2, 3, 3, 5 },
{ 3, 5, 1, 3, 7, 5, 3, 6, 4 },
{ 3, 5, 4, 3, 2, 6, 4, 4, 3 },
{ 6, 2, 4, 3, 4, 5, 4, 5, 1 }
};
foo(maze);
}
Aucun commentaire:
Enregistrer un commentaire