-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAss2.cpp
More file actions
132 lines (94 loc) · 2.44 KB
/
Copy pathAss2.cpp
File metadata and controls
132 lines (94 loc) · 2.44 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <bits/stdc++.h>
using namespace std;
struct Node {
int x, y;
int g, h, f;
};
int heuristic(int x1, int y1, int x2, int y2){
return abs(x1 - x2) + abs(y1 - y2);
}
void aStar(vector<vector<int>>& grid,int sx, int sy,int gx, int gy)
{
int n = grid.size();
int m = grid[0].size();
vector<vector<bool>> visited(n,vector<bool>(m, false));
priority_queue<
pair<int, Node>,
vector<pair<int, Node>>,
greater<pair<int, Node>>
> pq;
Node start;
start.x = sx;
start.y = sy;
start.g = 0;
start.h = heuristic(sx, sy, gx, gy);
start.f = start.g + start.h;
pq.push({start.f, start});
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};
cout << "\nPath:\n";
while(!pq.empty())
{
Node current = pq.top().second;
pq.pop();
int x = current.x;
int y = current.y;
if(visited[x][y])
{
continue;
}
visited[x][y] = true;
cout << "(" << x << "," << y << ") ";
// Goal reached
if(x == gx && y == gy)
{
cout << "\nGoal Reached";
return;
}
// Explore neighbours
for(int i=0; i<4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && ny >= 0 &&
nx < n && ny < m &&
grid[nx][ny] == 0 &&
!visited[nx][ny])
{
Node next;
next.x = nx;
next.y = ny;
next.g = current.g + 1;
next.h = heuristic(nx, ny, gx, gy);
next.f = next.g + next.h;
pq.push({next.f, next});
}
}
}
cout << "\nNo Path Found";
}
int main()
{
int n, m;
cout << "Enter rows and columns: ";
cin >> n >> m;
vector<vector<int>> grid(n,
vector<int>(m));
cout << "\nEnter Grid:\n";
cout << "0 = Free Cell\n";
cout << "1 = Blocked Cell\n\n";
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cin >> grid[i][j];
}
}
int sx, sy, gx, gy;
cout << "\nEnter Start Position: ";
cin >> sx >> sy;
cout << "Enter Goal Position: ";
cin >> gx >> gy;
aStar(grid, sx, sy, gx, gy);
return 0;
}