patternpythonMinor
Depth and breadth first search
Viewed 0 times
depthsearchbreadthfirstand
Problem
I am practicing interview questions, I wrote this code to perform BFS and DFS on a graph in Python.
How can it be optimized, and how can it be made more readable?
How can it be optimized, and how can it be made more readable?
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def add_edge(self, u, v):
self.graph[u].append(v)
def dfs(self, node):
visited = [False for i in range(len(self.graph))]
stack = []
stack.append(node)
visited[node] = True
while stack:
node = stack.pop()
print node
for i in self.graph[node]:
if visited[i] == False:
visited[i] = True
stack.append(i)
def Bfs(self, node):
visited = [False for i in range(len(self.graph))]
queue = []
queue.append(node)
visited[node] = True
while queue:
node = queue.pop(0)
print node
for i in self.graph[node]:
if not visited[i]:
queue.append(i)
visited[i] = TrueSolution
Small syntactical changes
You wrote this one time:
And used the correct idiom the second time:
Performance
According to here, generating a list with multiplication is the fastest way, so change both occurrences of:
to:
Bfs should at least be bfs. Some would probably argue that you should spell out depth_first_search and breadth_first_search entirely. I personally like small names, but regardless, the capital B should not be there.You wrote this one time:
if visited[i] == False:And used the correct idiom the second time:
if not visited[i]:Performance
According to here, generating a list with multiplication is the fastest way, so change both occurrences of:
visited = [False for i in range(len(self.graph))]to:
visited = [False] * len(self.graph)Code Snippets
if visited[i] == False:if not visited[i]:visited = [False for i in range(len(self.graph))]visited = [False] * len(self.graph)Context
StackExchange Code Review Q#159237, answer score: 3
Revisions (0)
No revisions yet.