bfs third try, repaired, need to print the path from start to goal

This commit is contained in:
trzmielewskiR 2022-04-07 23:04:25 +02:00
parent 3044a71592
commit 50258414f7
2 changed files with 39 additions and 42 deletions

View File

@ -1,27 +1,46 @@
class BreadthSearchAlgorithm:
def __init__(self, graph, start, target):
self.graph = graph
def __init__(self, start, target):
self.graph = self.getData()
self.start = start
self.target = target
def bfs(self):
queue = [[self.start]]
print("It's showtime")
can_go = [self.start]
visited = []
if self.start == self.target:
return
while queue:
path = queue.pop(0)
node = path[-1]
print("Start = Target")
return -1
while can_go != []:
node = can_go.pop(0)
if node not in visited:
neighbours = self.graph
for neighbour in neighbours:
next_path = list(path)
next_path.append(neighbour)
queue.append(next_path)
if neighbour == self.target:
return next_path
visited.append(node)
if node == self.target:
return visited
neighbours = self.graph.get(node, [])
for neighbour in neighbours:
can_go.append(neighbour)
print(visited)
return -1
return "Path found"
def getData(self):
with open("data.txt", "r") as f:
matrix = [
[int(x) for x in line.split(",") if x != "\n"] for line in f.readlines()
]
adj = {}
for yi, yvalue in enumerate(matrix):
for xi, xvalue in enumerate(matrix):
if xi - 1 >= 0 and matrix[yi][xi - 1] == 0:
adj[(xi, yi)] = adj.get((xi, yi), []) + [(xi - 1, yi)]
if xi + 1 < len(matrix[yi]) and matrix[yi][xi + 1] == 0:
adj[(xi, yi)] = adj.get((xi, yi), []) + [(xi + 1, yi)]
if yi - 1 >= 0 and matrix[yi - 1][xi] == 0:
adj[(xi, yi)] = adj.get((xi, yi), []) + [(xi, yi - 1)]
if yi + 1 < len(matrix) and matrix[yi + 1][xi] == 0:
adj[(xi, yi)] = adj.get((xi, yi), []) + [(xi, yi + 1)]
return adj

28
main.py
View File

@ -144,37 +144,15 @@ class Game():
# pygame.quit()
# if __name__ == '__main__':
# main()
def graph():
with open('data.txt', 'r') as f:
matrix = [[int(x) for x in line.split(',') if x != '\n'] for line in f.readlines()]
adj = {}
for yi, yvalue in enumerate(matrix):
for xi, xvalue in enumerate(matrix):
if xi - 1 >= 0 and matrix[yi][xi - 1] == 0:
adj[(xi, yi)] = adj.get((xi, yi), []) + [(xi - 1, yi)]
if xi + 1 < len(matrix[yi]) and matrix[yi][xi + 1] == 0:
adj[(xi, yi)] = adj.get((xi, yi), []) + [(xi + 1, yi)]
if yi - 1 >= 0 and matrix[yi - 1][xi] == 0:
adj[(xi, yi)] = adj.get((xi, yi), []) + [(xi, yi - 1)]
if yi + 1 < len(matrix) and matrix[yi + 1][xi] == 0:
adj[(xi, yi)] = adj.get((xi, yi), []) + [(xi, yi + 1)]
l = sorted(list(adj.items()), key=lambda x: (x[0]))
print(*l, sep='\n')
return l
start_node = (0, 2)
target_node = (0, 2)
target_node = (5, 3)
find_path = BreadthSearchAlgorithm(start_node, target_node)
# create the game object
g = Game()
g.show_start_screen()
while True:
g.new()
path_found = find_path.bfs()
g.run()
g.show_go_screen()
SearchBfs.BreadthSearchAlgorithm(graph, start_node, target_node)