-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrat_Maze_Using_Graph.cpp
More file actions
101 lines (83 loc) · 2.21 KB
/
Copy pathrat_Maze_Using_Graph.cpp
File metadata and controls
101 lines (83 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <queue>
#include "iostream"
#include "vector"
using namespace std;
struct Edge {
int source,destination;
};
class Graph{
int V;
vector<vector<int>> adjList;
public:
Graph(vector<Edge> edges,int V){
this->V = V;
adjList.resize(V);
for(auto i : edges){
adjList[i.source].push_back(i.destination);
// adjList[i.destination].push_back(i.source);
}
}
void BFS(int x1,int y1,int x2,int y2,int N);
void printGraph();
};
void Graph :: printGraph()
{
for (int i = 0; i < V; i++)
{
cout << i << " -- ";
for (int v : adjList[i])
cout <<"->"<< v << " ";
cout << endl;
}
}
void Graph :: BFS(int x1,int y1,int x2,int y2,int N){
int s = (x1 * N) + y1; int destination = (x2 * N ) + y1;
vector<bool> discovered(V, false);
for(int i = 0; i < V; i++)
discovered[i] = false;
queue <int> q;
discovered[s] = true;
q.push(s);
while(!q.empty())
{
s = q.front(); q.pop();
if(s == destination) {cout <<"Path exists"; return;}
for (auto j : adjList[s]) {
if(!discovered[j]){
discovered[j] = true;
q.push(j);
}
}
}
cout <<"Path does not exists";
}
bool valid(int x,int y,int N){
if(x <0 || y < 0 || x >= N || y >= N) return false;
return true;
}
int main()
{
vector<Edge> edges ;
int maze[4][4] = { { 1, 0, 0, 1 },
{ 1, 1, 0, 1 },
{ 0, 1, 0, 1},
{ 1, 1, 1, 1 } };
int N = (*(&maze + 1) - maze);
int row[] = {1,-1,0,0};
int column [] = {0,0,-1,1};
int sizeof_Row = (*(&row + 1) - row);
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
for (int k = 0; k < sizeof_Row; ++k) {
int next_X = i + row[k]; int next_Y = j + column[k];
if(valid(next_X,next_Y,N) && maze[next_X][next_Y] && maze[i][j] ) edges.push_back({(i * N) + j,(next_X * N ) + next_Y });
}
}
}
int V = N * N;
Graph graph(edges, V);
// graph.printGraph();
graph.BFS(3,0,0,3,N);
cout << "\n";
return 0;
}