Skip to content

Instantly share code, notes, and snippets.

@GEEGABYTE1
Created August 2, 2021 16:59
Show Gist options
  • Save GEEGABYTE1/8221edb1ff98b6a586bb6067841a89ad to your computer and use it in GitHub Desktop.
Save GEEGABYTE1/8221edb1ff98b6a586bb6067841a89ad to your computer and use it in GitHub Desktop.
Graph Search Traversal Algorithms
def bfs(graph, start_vertex, target):
path = [start_vertex]
vertex_and_path = [start_vertex, path]
bfs_queue = [vertex_and_path]
visited = set()
paths = {}
counter = 0
while bfs_queue:
print('-'*24)
current_vertex, path = bfs_queue.pop()
visited.add(current_vertex)
print(path)
for neighbour in graph[current_vertex]:
if not neighbour in visited:
if neighbour == target:
path.append(neighbour)
bfs_queue.append([neighbour, path])
continue
else:
path.append(neighbour)
bfs_queue.append([neighbour, path])
paths[counter] = path
counter += 1
def dfs(graph, current_vertex, target, visited=None):
if visited == None:
visited = []
visited.append(current_vertex)
for neighbour in graph[current_vertex]:
if not neighbour in visited:
path = dfs(graph, neighbour, target, visited)
if path == None:
print(visited)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment