Repository navigation
Expand file tree
/
Copy pathAlgorithms.py
More file actions
117 lines (80 loc) · 3.1 KB
/
Copy pathAlgorithms.py
File metadata and controls
117 lines (80 loc) · 3.1 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
from Maze import Maze,A_StarMaze
from Node import Node
def dfs(path, visited, graph, node, target):
visited.append(node)
path.append(node)
if (node == target):
return path
x = node[0]
y = node[1]
if graph[node] == [] :
path.pop()
return []
if (x,y-1) in graph[node] and (x,y-1) not in visited :
testPath = dfs(path,visited, graph, (x,y-1),target)
if testPath != [] :
return testPath
if (x+1,y) in graph[node] and (x+1,y) not in visited :
testPath = dfs(path,visited, graph, (x+1,y),target)
if testPath != [] :
return testPath
if (x,y+1) in graph[node] and (x,y+1) not in visited :
testPath = dfs(path,visited, graph, (x,y+1),target)
if testPath != [] :
return testPath
if (x-1,y) in graph[node] and (x-1,y) not in visited:
testPath = dfs(path, visited,graph, (x-1,y),target)
if testPath != [] :
return testPath
path.pop()
return []
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = []
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return (path,visited)
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
# Mark the vertex as visited
visited.append(vertex)
def a_star(maze,start,target):
opened = []
closed = []
visited = []
opened.append(start)
graph = maze.return_maze()
while (len(opened) > 0):
currentNode = min(opened,key=lambda x: x.return_fcost())
#print('cur node = ',currentNode)
opened.remove(currentNode)
closed.append(currentNode)
visited.append(currentNode.return_coordinate())
if (currentNode == target):
return (maze.retrace_path(start,currentNode),visited)
try :
neighbours = graph[currentNode]
except :
print('ERORR')
print('same =', maze.return_maze() == graph)
print(maze.return_maze())
break
for n in neighbours:
if n in closed:
continue
shorterPathExist = n.calculate_fcost(currentNode,target) < n.return_fcost()
if (shorterPathExist) or (n not in opened):
n.update_fcost(currentNode,target)
n.set_parent(currentNode)
if n not in opened:
opened.append(n)