class Graph:
def __init__(self):
self.nodes = {}
def add_node(self, value):
if value not in self.nodes:
self.nodes[value] = []
def add_edge(self, from_node, to_node):
if from_node in self.nodes and to_node in self.nodes:
self.nodes[from_node].append(to_node)
self.nodes[to_node].append(from_node)
def has_path(self, start, end):
visited = set()
return self._dfs(start, end, visited)
def _dfs(self, current, target, visited):
if current == target:
return True
visited.add(current)
for neighbor in self.nodes[current]:
if neighbor not in visited and self._dfs(neighbor, target, visited):
return True
return False
graph = Graph()
for node in ["A", "B", "C", "D"]:
graph.add_node(node)
graph.add_edge("A", "B")
graph.add_edge("A", "C")
graph.add_edge("B", "D")
print(graph.has_path("A", "D"))