-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolve.c
88 lines (61 loc) · 1.49 KB
/
solve.c
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
#include "solve.h"
#include "string.h"
/* Recursive function to find a path through a maze */
int look(struct maze* maze, struct pos pos) {
int i, n;
/* Set new position based on direction */
switch (pos.dir) {
case MOVE_UP:
pos.y -= 1;
break;
case MOVE_DOWN:
pos.y += 1;
break;
case MOVE_LEFT:
pos.x -= 1;
break;
case MOVE_RIGHT:
pos.x += 1;
break;
default:
break;
}
/* Check new position */
if (pos.y < 0 || pos.y >= maze->numrows)
return MAZE_NOWAY;
else if (pos.x < 0 || pos.x >= strlen(maze->map[pos.y]))
return MAZE_NOWAY;
else if (maze->map[pos.y][pos.x] == MAZE_WALL)
return MAZE_NOWAY;
else if (maze->map[pos.y][pos.x] == MAZE_EXIT)
return MAZE_FOUNDEXIT;
else if (maze->map[pos.y][pos.x] == MAZE_ENTRANCE)
return MAZE_NOEXIT;
/* Try all the three directions other than backwards */
pos.dir -= 1;
if (pos.dir < 0)
pos.dir += 4;
for (i = 0; i < 3; ++i) {
maze->map[pos.y][pos.x] = MAZE_TRAIL; /* Leave trail through maze */
n = look(maze, pos);
if (n) {
if (n == MAZE_NOEXIT)
maze->map[pos.y][pos.x] = MAZE_PATH; /* No exit, so clear trail */
return n;
}
pos.dir += 1;
if (pos.dir > 3)
pos.dir -= 4;
}
/* Dead end, so clear trail and return */
maze->map[pos.y][pos.x] = MAZE_PATH;
return 0;
}
/* Function to find a path through a maze */
int solve(struct maze* maze) {
struct pos pos;
pos.x = maze->startx;
pos.y = maze->starty;
pos.dir = maze->initdir;
return look(maze, pos);
}