forked from hacktoberfest2k20/DataStructures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lees_algo.cpp
98 lines (75 loc) · 1.77 KB
/
Lees_algo.cpp
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
//THIS ALGORITHM IS KNOWN AS LEE'S ALGORITHM
// TIME COMPEXITY-Since it is an MxN grid
// the time complexity is O(MN)
#include <iostream>
#include <queue>
#include <climits>
#include <cstring>
using namespace std;
#define M 10
#define N 10
struct Node
{
int x, y, dist;
};
int row[] = { -1, 0, 0, 1 };
int col[] = { 0, -1, 1, 0 };
bool isValid(int mat[][N], bool visited[][N], int row, int col)
{
return (row >= 0) && (row < M) && (col >= 0) && (col < N)
&& mat[row][col] && !visited[row][col];
}
void BFS(int mat[][N], int i, int j, int x, int y)// BFS algorithm
{
bool visited[M][N]
memset(visited, false, sizeof visited);
queue<Node> q;
visited[i][j] = true;
q.push({i, j, 0});
int min_dist = INT_MAX;
while (!q.empty())
{
Node node = q.front();
q.pop();
int i = node.x, j = node.y, dist = node.dist;
if (i == x && j == y)
{
min_dist = dist;
break;
}
for (int k = 0; k < 4; k++)
{
if (isValid(mat, visited, i + row[k], j + col[k]))
{
visited[i + row[k]][j + col[k]] = true;
q.push({ i + row[k], j + col[k], dist + 1 });
}
}
}
if (min_dist != INT_MAX)
cout << "The shortest path from source to destination "
"has length " << min_dist;
else
cout << "Destination can't be reached from given source";
}
int main()
{
// input maze
int mat[M][N] =
{
{ 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 },
{ 0, 1, 1, 1, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 1, 0, 1, 1, 1, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 0, 1, 1, 0, 1 },
{ 0, 0, 0, 1, 0, 0, 0, 1, 0, 1 },
{ 1, 0, 1, 1, 1, 0, 0, 1, 1, 0 },
{ 0, 0, 0, 0, 1, 0, 0, 1, 0, 1 },
{ 0, 1, 1, 1, 1, 1, 1, 1, 0, 0 },
{ 1, 1, 1, 1, 1, 0, 0, 1, 1, 1 },
{ 0, 0, 1, 0, 0, 1, 1, 0, 0, 1 },
};
// Find shortest path from source (0, 0) to
// destination (7, 5)
BFS(mat, 0, 0, 7, 5);
return 0;
}