-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmaze.py
85 lines (72 loc) · 3.65 KB
/
maze.py
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
'''defining constant'''
CORRIDOR = 0
WALL = 1
DESTINATION = 2
VISITED = 3
BLOCKED = 4
def findpath(_maze, y, x):
path_stack = [] # pushing the starting point to the path stack
path_stack.append([y, x])
_maze[y][x] = VISITED
while True:
coor = path_stack.pop()
if _maze[coor[0]][coor[1] + 1] == DESTINATION or _maze[coor[0]][coor[1] - 1] == DESTINATION \
or _maze[coor[0] + 1][coor[1]] == DESTINATION or _maze[coor[0] - 1][coor[1]] == DESTINATION:
for n in range(len(_maze)):
_maze[n] = [CORRIDOR if x == BLOCKED else x for x in _maze[n]]
break
else:
if _maze[coor[0] + 1][coor[1]] == CORRIDOR: # checking bottom block
path_stack.append(coor)
path_stack.append([coor[0] + 1, coor[1]])
_maze[coor[0] + 1][coor[1]] = VISITED
elif _maze[coor[0]][coor[1] + 1] == CORRIDOR: # checking right block
path_stack.append(coor)
path_stack.append([coor[0], coor[1] + 1])
_maze[coor[0]][coor[1] + 1] = VISITED
elif _maze[coor[0]][coor[1] - 1] == CORRIDOR: # checking left block
path_stack.append(coor)
path_stack.append([coor[0], coor[1] - 1])
_maze[coor[0]][coor[1] - 1] = VISITED
elif _maze[coor[0] - 1][coor[1]] == CORRIDOR: # checking top block
path_stack.append(coor)
path_stack.append([coor[0] - 1, coor[1]])
_maze[coor[0] - 1][coor[1]] = VISITED
else: # if all place is blocked
try:
invalid_route = path_stack.pop()
except:
return []
_maze[invalid_route[0]][invalid_route[1]] = BLOCKED
return _maze
if __name__ == "__main__":
maze = [
[1, 1, 1, 1, 1, 1, 1, 1,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 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 2],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]
print(maze)
X, Y = map(int, input("X Y 를 입력하시오 \n").split())
new_maze = findpath(maze, Y, X)
if new_maze != []:
[print(i) for i in new_maze]
else:
print("there is no path")