I apologize for the confusion. Here's an updated version of the Q6Graph class that should meet your requirements:
class Q6Graph:
def __init__(self):
self.vertices = {} # Dictionary to store vertices and their adjacent edges
def add_vertex(self, vertex_id):
'''
Adds a vertex to the graph with the given id.
'''
if vertex_id not in self.vertices:
self.vertices[vertex_id] = []
def add_directed_edge_with_weight(self, source_id, destination_id, weight):
'''
Adds a directed edge from the vertex with id 'source_id' to the vertex
with id 'destination_id' and applies a weight.
'''
if source_id in self.vertices and destination_id in self.vertices:
edge = (destination_id, weight)
self.vertices[source_id].append(edge)
def get_iterative_dfs_path_edge_weight(self, start_id, stop_id):
'''
Returns the sum of edge weights between start and stop vertices
using an iterative Depth First Search (DFS).
'''
stack = [(start_id, 0)] # Stack to track visited vertices and their accumulated weights
while stack:
current_vertex, path_weight = stack.pop()
if current_vertex == stop_id:
return path_weight
for neighbor, edge_weight in self.vertices[current_vertex]:
stack.append((neighbor, path_weight + edge_weight))
return None
Please note that this implementation assumes that the graph is connected, and there is a valid path between the start and stop vertices.
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案 |