Skip to content

Instantly share code, notes, and snippets.

@kv-kunalvyas
Created February 29, 2016 23:31
Show Gist options
  • Save kv-kunalvyas/17727e1e0cb2ea973e5a to your computer and use it in GitHub Desktop.
Save kv-kunalvyas/17727e1e0cb2ea973e5a to your computer and use it in GitHub Desktop.
Graphs
#TODO: bidirectional bfs/dfs,
directedGraph = {0: [1,4], 1: [3], 2: [], 3: [0,1,4], 4: [0,3]}
undirectedGraph = {0: [1,4], 1: [0,3], 2: [], 3: [1,4], 4: [0,3]}
completeGraph = {0:[1,2,3], 1:[0,2,3], 2:[0,1,3], 3:[0,1,2]}
def bfs(graph, start, path=[]):
queue = [start]
while queue:
visited = queue.pop(0)
if visited not in path:
path += [visited]
if visited in graph:
queue += graph[visited]
return path
def dfs(graph, start, path=[]):
queue = [start]
while queue:
visited = queue.pop(0)
if visited not in path:
path += [visited]
if visited in graph:
queue = graph[visited] + queue
return path
def isComplete(graph):
elements=[]
for x in graph:
elements.append(x)
elements.sort()
for x in elements:
y = graph[x] + [x]
y.sort()
if y != elements:
return False
return True
print isComplete(directedGraph)
print isComplete(completeGraph)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment