Created
August 2, 2021 16:59
-
-
Save GEEGABYTE1/8221edb1ff98b6a586bb6067841a89ad to your computer and use it in GitHub Desktop.
Graph Search Traversal Algorithms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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