-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortest_path.cpp
More file actions
74 lines (65 loc) · 1.39 KB
/
Shortest_path.cpp
File metadata and controls
74 lines (65 loc) · 1.39 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
#include <iostream>
#include <vector>
#define SIZE 6
using namespace std;
vector <int> path_length;
int maze[SIZE][SIZE];
void solution (int,int);
void solution (int,int,int);
void solution(int r,int c)
{
solution(r+1,c,1);
solution(r,c+1,1);
solution(r-1,c,1);
solution(r,c-1,1);
}
void solution(int r,int c,int n)
{
if((r==0 || r==SIZE-1 || c==0 || c==SIZE-1) && maze[r][c] == 0)
{
path_length.push_back(n);
}
if((r>0 && r<SIZE) && (c>0 && c<SIZE) && maze[r][c] == 0)
{
maze[r][c] = 2;
solution(r+1,c,n+1);
solution(r,c+1,n+1);
solution(r-1,c,n+1);
solution(r,c-1,n+1);
maze[r][c] = 0;
}
}
int main()
{
int small;
int i,j,k,l;
cout<<"Enter:"<<endl;
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
cin>>maze[i][j];
if(maze[i][j] == 1)
{
k = i; l = j;
}
}
}
solution(k,l);
if(path_length.empty())
{
cout<<"No path"<<endl;
return 0;
}
small = path_length[0];
for(i=0;i<path_length.size();i++)
{
if(path_length[i]<small)
{
small = path_length[i];
}
}
cout<<endl;
cout<<"Answer:"<<small<<endl;
return 0;
}