-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortest.cpp
More file actions
91 lines (61 loc) · 1.79 KB
/
shortest.cpp
File metadata and controls
91 lines (61 loc) · 1.79 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
#include <bits/stdc++.h>
using namespace std;
#define M 10
#define N 10
bool isSafe(int mat[M][N], int visited[M][N], int x, int y)
{
if (mat[x][y] == 0 || visited[x][y])
return false;
return true;
}
bool isValid(int x, int y)
{
if (x < M && y < N && x >= 0 && y >= 0)
return true;
return false;
}
void findShortestPath(int mat[M][N], int visited[M][N], int i, int j,
int x, int y, int& min_dist, int dist)
{
if (i == x && j == y)
{
min_dist = min(dist, min_dist);
return;
}
visited[i][j] = 1;
if (isValid(i + 1, j) && isSafe(mat, visited, i + 1, j))
findShortestPath(mat, visited, i + 1, j, x, y, min_dist, dist + 1);
if (isValid(i, j + 1) && isSafe(mat, visited, i, j + 1))
findShortestPath(mat, visited, i, j + 1, x, y, min_dist, dist + 1);
if (isValid(i - 1, j) && isSafe(mat, visited, i - 1, j))
findShortestPath(mat, visited, i - 1, j, x, y, min_dist, dist + 1);
if (isValid(i, j - 1) && isSafe(mat, visited, i, j - 1))
findShortestPath(mat, visited, i, j - 1, x, y, min_dist, dist + 1);
visited[i][j] = 0;
}
int main()
{
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 },
};
int visited[M][N];
memset(visited, 0, sizeof visited);
int min_dist = INT_MAX;
findShortestPath(mat, visited, 0, 0, 7, 5, min_dist, 0);
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";
return 0;
}