-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathFinder.cpp
More file actions
111 lines (90 loc) · 2.08 KB
/
pathFinder.cpp
File metadata and controls
111 lines (90 loc) · 2.08 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
102
103
104
105
106
107
108
109
110
111
#include <bits/stdc++.h>
using namespace std;
#define N 4
class Graph {
int V;
list<int>* adj;
public:
Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void addEdge(int s, int d);
bool BFS(int s, int d);
};
void Graph::addEdge(int s, int d)
{
adj[s].push_back(d);
}
bool Graph::BFS(int s, int d)
{
if (s == d)
return true;
bool* visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;
list<int> queue;
visited[s] = true;
queue.push_back(s);
list<int>::iterator i;
while (!queue.empty()) {
s = queue.front();
queue.pop_front();
for (
i = adj[s].begin(); i != adj[s].end(); ++i) {
if (*i == d)
return true;
if (!visited[*i]) {
visited[*i] = true;
queue.push_back(*i);
}
}
}
return false;
}
bool isSafe(int i, int j, int M[][N])
{
if (
(i < 0 || i >= N)
|| (j < 0 || j >= N)
|| M[i][j] == 0)
return false;
return true;
}
bool findPath(int M[][N])
{
int s, d;
int V = N * N + 2;
Graph g(V);
int k = 1;
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (M[i][j] != 0) {
if (isSafe(i, j + 1, M))
g.addEdge(k, k + 1);
if (isSafe(i, j - 1, M))
g.addEdge(k, k - 1);
if (i < N - 1 && isSafe(i + 1, j, M))
g.addEdge(k, k + N);
if (i > 0 && isSafe(i - 1, j, M))
g.addEdge(k, k - N);
}
if (M[i][j] == 1)
s = k;
if (M[i][j] == 2)
d = k;
k++;
}
}
return g.BFS(s, d);
}
int main()
{
int M[N][N] = { { 0, 3, 0, 1 },
{ 3, 0, 3, 3 },
{ 2, 3, 3, 3 },
{ 0, 3, 3, 3 } };
(findPath(M) == true) ? cout << "Path Found" : cout << "No Possible Path" << endl;
return 0;
}