-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathmaze.py
More file actions
97 lines (67 loc) · 2.14 KB
/
maze.py
File metadata and controls
97 lines (67 loc) · 2.14 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
92
93
94
95
from typing import List, Any
class Stack:
def __init__(self) -> None:
self.stack:List[Any] = list()
def is_empty(self) -> bool:
return len(self.stack) == 0
def size(self) -> int:
return len(self.stack)
def push(self, item:Any) -> None:
self.stack.append(item)
def peek(self) -> Any:
if self.is_empty():
raise Exception('Stack is empty')
return self.stack[len(self.stack) - 1]
def pop(self) -> Any:
if self.is_empty():
raise Exception('Stack is empty')
return self.stack.pop()
size: int = 5
matrix = [[0 for x in range(size)] for y in range(size)]
'''
0 - not visited
1 - visited
2 - obstacle
'''
# place maze obstacles
matrix[0][2] = 2
matrix[0][3] = 2
matrix[1][0] = 2
matrix[2][2] = 2
matrix[2][3] = 2
matrix[2][4] = 2
matrix[3][1] = 2
matrix[4][3] = 2
# starting position
matrix[0][0] = 1
stack = Stack()
stack.push([0, 0])
def path_finder(matrix:List[List[int]], stack:Stack) -> None:
_move(matrix, stack)
def _move(matrix:List[List[int]], stack:Stack) -> None:
if stack.is_empty():
print('Path not found')
else:
x, y = stack.peek()
if x == len(matrix) - 1 and y == len(matrix[x]) - 1:
print('Path found')
elif y < len(matrix[x]) - 1 and matrix[x][y + 1] == 0:
_add_coordinates_to_stack(matrix, stack, x, y + 1)
_move(matrix, stack)
elif y > 0 and matrix[x][y - 1] == 0:
_add_coordinates_to_stack(matrix, stack, x, y - 1)
_move(matrix, stack)
elif x > 0 and matrix[x - 1][y] == 0:
_add_coordinates_to_stack(matrix, stack, x - 1, y)
_move(matrix, stack)
elif x < len(matrix) - 1 and matrix[x + 1][y] == 0:
_add_coordinates_to_stack(matrix, stack, x + 1, y)
_move(matrix, stack)
else:
stack.pop()
_move(matrix, stack)
def _add_coordinates_to_stack(matrix:List[List[int]], stack:Stack, x:int, y:int) -> None:
matrix[x][y] = 1
stack.push([x, y])
if __name__ == "__main__":
path_finder(matrix, stack)