Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/dfs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
class Graph:
def __init__(self, vertices: list[int], edges: list[tuple[int, int]]):
self.vertices = vertices
self.edges = edges
self.passage= []

def __iter__(self):
if not self.passage:
self.dfs()
return iter(self.passage)

def dfs(self):
passed = set()
self.passage = []

def step(vertex):
if vertex not in passed:
passed.add(vertex)
self.passage.append(vertex)

neighbors = []
for edge in self.edges:
if edge[0] == vertex:
neighbors.append(edge[1])
elif edge[1] == vertex:
neighbors.append(edge[0])

for neighbor in neighbors:
step(neighbor)

for vertex in self.vertices:
if vertex not in passed:
step(vertex)

return self.passage
22 changes: 22 additions & 0 deletions test/dfs_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from src.dfs import Graph

def test_simple_graph():
vertices = [1, 2, 3, 4]
edges = [(1, 2), (2, 3), (3, 4)]
graph = Graph(vertices, edges)
result = list(graph)
assert result == [1, 2, 3, 4]

def test_single_vertex():
vertices = [1]
edges = []
graph = Graph(vertices, edges)
result = list(graph)
assert result == [1]

def test_empty_graph():
vertices = []
edges = []
graph = Graph(vertices, edges)
result = list(graph)
assert result == []