Additional Question
Please try to provide the source code or pseudo code of the following
questions.
(1)Try to write an algorithm based on graph's depth-first search
strategy to determine whether there exists a path from vertex vi to
vertex vj (where i is not equal to j) in a directed graph stored in
adjacency list (i.e., node array with arc chain) form.
function hasPathDFS(graph, start, end, visited=None):
if visited is None:
visited = set()
if start == end:
return True
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
if hasPathDFS(graph, neighbor, end, visited):
return True
return False
(2)How to implement the Question (1) using breadth-first search
method?
function hasPathBFS(graph, start, end):
queue = [start]
visited = set()
visited.add(start)
while queue is not empty:
current = queue.dequeue()
if current == end:
return True
for neighbor in graph[current]:
if neighbor not in visited:
visited.add(neighbor)
queue.enqueue(neighbor)
return False