-
Notifications
You must be signed in to change notification settings - Fork 0
/
ratmaze_backtracking.cpp
74 lines (65 loc) · 1.17 KB
/
ratmaze_backtracking.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
// rat maze
#include<iostream>
#define SIZE 5
int maze[SIZE][SIZE];
using namespace std;
void print();
void print()
{
int i,j;
for(i=0;i<SIZE;i++)
{
for(j=0;j<SIZE;j++)
{
cout<<maze[i][j]<<" ";
}
cout<<endl;
}
}
int findpath(int r, int c, int dr, int dc)
{
if((r>=0 && r<SIZE) && (c>=0 && r<SIZE) && (maze[r][c] != 9) && (maze[r][c] == 2))
{
maze[r][c] = 7;
return 1;
}
if((r>=0 && r<SIZE) && (c>=0 && r<SIZE) && (maze[r][c] != 9))
{
maze[r][c] = 7;
if(findpath(r+1,c,dr,dc))
return 1;
if(findpath(r,c+1,dr,dc))
return 1;
maze[r][c] = 0;
return 0;
}
return 0;
}
int main()
{
//int size;
//cout<<"Enter maze size:";
//cin>>size;
//cout<<endl;
//int maze[size][size];
int i,j,k,l,m,n;
cout<<"Enter maze( 1->rat , 2->destination , 0->free path , 9->dead end):"<<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;}
if(maze[i][j] == 2)
{ m = i; n = j;}
}
}
cout<<k<<" "<<l<<endl;
cout<<m<<" "<<n<<endl;
if(findpath(k,l,m,n))
print();
else
cout<<"No solution"<<endl;
return 0;
}