mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
This commit is contained in:
@@ -12,11 +12,11 @@ from modules import Vertex, vals_to_vets
|
||||
|
||||
|
||||
class GraphAdjList:
|
||||
"""Undirected graph class based on adjacency list"""
|
||||
"""Undirected graph class implemented with an adjacency list"""
|
||||
|
||||
def __init__(self, edges: list[list[Vertex]]):
|
||||
"""Constructor"""
|
||||
# Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
# Adjacency list: key is a vertex, value is the list of all its neighbors
|
||||
self.adj_list = dict[Vertex, list[Vertex]]()
|
||||
# Add all vertices and edges
|
||||
for edge in edges:
|
||||
@@ -29,7 +29,7 @@ class GraphAdjList:
|
||||
return len(self.adj_list)
|
||||
|
||||
def add_edge(self, vet1: Vertex, vet2: Vertex):
|
||||
"""Add edge"""
|
||||
"""Add an edge"""
|
||||
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
|
||||
raise ValueError()
|
||||
# Add edge vet1 - vet2
|
||||
@@ -37,7 +37,7 @@ class GraphAdjList:
|
||||
self.adj_list[vet2].append(vet1)
|
||||
|
||||
def remove_edge(self, vet1: Vertex, vet2: Vertex):
|
||||
"""Remove edge"""
|
||||
"""Remove an edge"""
|
||||
if vet1 not in self.adj_list or vet2 not in self.adj_list or vet1 == vet2:
|
||||
raise ValueError()
|
||||
# Remove edge vet1 - vet2
|
||||
@@ -45,34 +45,34 @@ class GraphAdjList:
|
||||
self.adj_list[vet2].remove(vet1)
|
||||
|
||||
def add_vertex(self, vet: Vertex):
|
||||
"""Add vertex"""
|
||||
"""Add a vertex"""
|
||||
if vet in self.adj_list:
|
||||
return
|
||||
# Add a new linked list in the adjacency list
|
||||
# Add a new list to the adjacency list
|
||||
self.adj_list[vet] = []
|
||||
|
||||
def remove_vertex(self, vet: Vertex):
|
||||
"""Remove vertex"""
|
||||
"""Remove a vertex"""
|
||||
if vet not in self.adj_list:
|
||||
raise ValueError()
|
||||
# Remove the linked list corresponding to vertex vet in the adjacency list
|
||||
# Remove the list corresponding to vertex vet from the adjacency list
|
||||
self.adj_list.pop(vet)
|
||||
# Traverse the linked lists of other vertices and remove all edges containing vet
|
||||
# Traverse the lists of the other vertices and remove all edges incident to vet
|
||||
for vertex in self.adj_list:
|
||||
if vet in self.adj_list[vertex]:
|
||||
self.adj_list[vertex].remove(vet)
|
||||
|
||||
def print(self):
|
||||
"""Print adjacency list"""
|
||||
"""Print the adjacency list"""
|
||||
print("Adjacency list =")
|
||||
for vertex in self.adj_list:
|
||||
tmp = [v.val for v in self.adj_list[vertex]]
|
||||
print(f"{vertex.val}: {tmp},")
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize undirected graph
|
||||
# Initialize the undirected graph
|
||||
v = vals_to_vets([1, 3, 2, 5, 4])
|
||||
edges = [
|
||||
[v[0], v[1]],
|
||||
@@ -83,29 +83,29 @@ if __name__ == "__main__":
|
||||
[v[3], v[4]],
|
||||
]
|
||||
graph = GraphAdjList(edges)
|
||||
print("\nAfter initialization, the graph is")
|
||||
print("\nGraph after initialization:")
|
||||
graph.print()
|
||||
|
||||
# Add edge
|
||||
# Vertices 1, 2 are v[0], v[2]
|
||||
# Add an edge
|
||||
# Vertices 1 and 2 are v[0] and v[2]
|
||||
graph.add_edge(v[0], v[2])
|
||||
print("\nAfter adding edge 1-2, the graph is")
|
||||
print("\nGraph after adding edge 1-2:")
|
||||
graph.print()
|
||||
|
||||
# Remove edge
|
||||
# Vertices 1, 3 are v[0], v[1]
|
||||
# Remove an edge
|
||||
# Vertices 1 and 3 are v[0] and v[1]
|
||||
graph.remove_edge(v[0], v[1])
|
||||
print("\nAfter removing edge 1-3, the graph is")
|
||||
print("\nGraph after removing edge 1-3:")
|
||||
graph.print()
|
||||
|
||||
# Add vertex
|
||||
# Add a vertex
|
||||
v5 = Vertex(6)
|
||||
graph.add_vertex(v5)
|
||||
print("\nAfter adding vertex 6, the graph is")
|
||||
print("\nGraph after adding vertex 6:")
|
||||
graph.print()
|
||||
|
||||
# Remove vertex
|
||||
# Remove a vertex
|
||||
# Vertex 3 is v[1]
|
||||
graph.remove_vertex(v[1])
|
||||
print("\nAfter removing vertex 3, the graph is")
|
||||
print("\nGraph after removing vertex 3:")
|
||||
graph.print()
|
||||
|
||||
@@ -12,19 +12,19 @@ from modules import Vertex, print_matrix
|
||||
|
||||
|
||||
class GraphAdjMat:
|
||||
"""Undirected graph class based on adjacency matrix"""
|
||||
"""Undirected graph class implemented with an adjacency matrix"""
|
||||
|
||||
def __init__(self, vertices: list[int], edges: list[list[int]]):
|
||||
"""Constructor"""
|
||||
# Vertex list, where the element represents the "vertex value" and the index represents the "vertex index"
|
||||
# Vertex list: elements are vertex values, and indices are vertex indices
|
||||
self.vertices: list[int] = []
|
||||
# Adjacency matrix, where the row and column indices correspond to the "vertex index"
|
||||
# Adjacency matrix: row and column indices correspond to vertex indices
|
||||
self.adj_mat: list[list[int]] = []
|
||||
# Add vertices
|
||||
# Add a vertex
|
||||
for val in vertices:
|
||||
self.add_vertex(val)
|
||||
# Add edges
|
||||
# Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
# Add an edge
|
||||
# Note that the entries in edges are vertex indices, corresponding to element indices in vertices
|
||||
for e in edges:
|
||||
self.add_edge(e[0], e[1])
|
||||
|
||||
@@ -33,9 +33,9 @@ class GraphAdjMat:
|
||||
return len(self.vertices)
|
||||
|
||||
def add_vertex(self, val: int):
|
||||
"""Add vertex"""
|
||||
"""Add a vertex"""
|
||||
n = self.size()
|
||||
# Add the value of the new vertex to the vertex list
|
||||
# Append the new vertex value to the vertex list
|
||||
self.vertices.append(val)
|
||||
# Add a row to the adjacency matrix
|
||||
new_row = [0] * n
|
||||
@@ -45,72 +45,72 @@ class GraphAdjMat:
|
||||
row.append(0)
|
||||
|
||||
def remove_vertex(self, index: int):
|
||||
"""Remove vertex"""
|
||||
"""Remove a vertex"""
|
||||
if index >= self.size():
|
||||
raise IndexError()
|
||||
# Remove the vertex at index from the vertex list
|
||||
# Remove the vertex at index `index` from the vertex list
|
||||
self.vertices.pop(index)
|
||||
# Remove the row at index from the adjacency matrix
|
||||
# Remove row `index` from the adjacency matrix
|
||||
self.adj_mat.pop(index)
|
||||
# Remove the column at index from the adjacency matrix
|
||||
# Remove column `index` from the adjacency matrix
|
||||
for row in self.adj_mat:
|
||||
row.pop(index)
|
||||
|
||||
def add_edge(self, i: int, j: int):
|
||||
"""Add edge"""
|
||||
# Parameters i, j correspond to the vertices element indices
|
||||
# Handle index out of bounds and equality
|
||||
"""Add an edge"""
|
||||
# Parameters i and j are element indices in vertices
|
||||
# Handle out-of-bounds or equal indices
|
||||
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
|
||||
raise IndexError()
|
||||
# In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., (i, j) == (j, i)
|
||||
# For an undirected graph, the adjacency matrix is symmetric about its main diagonal: entries (i, j) and (j, i) are equal
|
||||
self.adj_mat[i][j] = 1
|
||||
self.adj_mat[j][i] = 1
|
||||
|
||||
def remove_edge(self, i: int, j: int):
|
||||
"""Remove edge"""
|
||||
# Parameters i, j correspond to the vertices element indices
|
||||
# Handle index out of bounds and equality
|
||||
"""Remove an edge"""
|
||||
# Parameters i and j are element indices in vertices
|
||||
# Handle out-of-bounds or equal indices
|
||||
if i < 0 or j < 0 or i >= self.size() or j >= self.size() or i == j:
|
||||
raise IndexError()
|
||||
self.adj_mat[i][j] = 0
|
||||
self.adj_mat[j][i] = 0
|
||||
|
||||
def print(self):
|
||||
"""Print adjacency matrix"""
|
||||
"""Print the adjacency matrix"""
|
||||
print("Vertex list =", self.vertices)
|
||||
print("Adjacency matrix =")
|
||||
print_matrix(self.adj_mat)
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize undirected graph
|
||||
# Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
# Initialize the undirected graph
|
||||
# Note that the entries in edges are vertex indices, corresponding to element indices in vertices
|
||||
vertices = [1, 3, 2, 5, 4]
|
||||
edges = [[0, 1], [0, 3], [1, 2], [2, 3], [2, 4], [3, 4]]
|
||||
graph = GraphAdjMat(vertices, edges)
|
||||
print("\nAfter initialization, the graph is")
|
||||
print("\nGraph after initialization:")
|
||||
graph.print()
|
||||
|
||||
# Add edge
|
||||
# Vertices 1, 2 have indices 0, 2 respectively
|
||||
# Add an edge
|
||||
# Vertices 1 and 2 have indices 0 and 2, respectively
|
||||
graph.add_edge(0, 2)
|
||||
print("\nAfter adding edge 1-2, the graph is")
|
||||
print("\nGraph after adding edge 1-2:")
|
||||
graph.print()
|
||||
|
||||
# Remove edge
|
||||
# Vertices 1, 3 have indices 0, 1 respectively
|
||||
# Remove an edge
|
||||
# Vertices 1 and 3 have indices 0 and 1, respectively
|
||||
graph.remove_edge(0, 1)
|
||||
print("\nAfter removing edge 1-3, the graph is")
|
||||
print("\nGraph after removing edge 1-3:")
|
||||
graph.print()
|
||||
|
||||
# Add vertex
|
||||
# Add a vertex
|
||||
graph.add_vertex(6)
|
||||
print("\nAfter adding vertex 6, the graph is")
|
||||
print("\nGraph after adding vertex 6:")
|
||||
graph.print()
|
||||
|
||||
# Remove vertex
|
||||
# Remove a vertex
|
||||
# Vertex 3 has index 1
|
||||
graph.remove_vertex(1)
|
||||
print("\nAfter removing vertex 3, the graph is")
|
||||
print("\nGraph after removing vertex 3:")
|
||||
graph.print()
|
||||
|
||||
@@ -15,30 +15,30 @@ from graph_adjacency_list import GraphAdjList
|
||||
|
||||
def graph_bfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
|
||||
"""Breadth-first traversal"""
|
||||
# Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
# Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
# Vertex traversal sequence
|
||||
res = []
|
||||
# Hash set for recording vertices that have been visited
|
||||
# Hash set recording visited vertices
|
||||
visited = set[Vertex]([start_vet])
|
||||
# Queue used to implement BFS
|
||||
# Use a queue to implement BFS
|
||||
que = deque[Vertex]([start_vet])
|
||||
# Starting from vertex vet, loop until all vertices are visited
|
||||
# Starting from start_vet, loop until all reachable vertices have been visited
|
||||
while len(que) > 0:
|
||||
vet = que.popleft() # Dequeue the front vertex
|
||||
res.append(vet) # Record visited vertex
|
||||
# Traverse all adjacent vertices of this vertex
|
||||
res.append(vet) # Record the visited vertex
|
||||
# Traverse all neighbors of this vertex
|
||||
for adj_vet in graph.adj_list[vet]:
|
||||
if adj_vet in visited:
|
||||
continue # Skip vertices that have been visited
|
||||
que.append(adj_vet) # Only enqueue unvisited vertices
|
||||
continue # Skip vertices that have already been visited
|
||||
que.append(adj_vet) # Enqueue only unvisited vertices
|
||||
visited.add(adj_vet) # Mark this vertex as visited
|
||||
# Return vertex traversal sequence
|
||||
# Return the vertex traversal sequence
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize undirected graph
|
||||
# Initialize the undirected graph
|
||||
v = vals_to_vets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
|
||||
edges = [
|
||||
[v[0], v[1]],
|
||||
@@ -55,10 +55,10 @@ if __name__ == "__main__":
|
||||
[v[7], v[8]],
|
||||
]
|
||||
graph = GraphAdjList(edges)
|
||||
print("\nAfter initialization, the graph is")
|
||||
print("\nGraph after initialization:")
|
||||
graph.print()
|
||||
|
||||
# Breadth-first traversal
|
||||
res = graph_bfs(graph, v[0])
|
||||
print("\nBreadth-first traversal (BFS) vertex sequence is")
|
||||
print("\nVertex sequence from breadth-first traversal (BFS):")
|
||||
print(vets_to_vals(res))
|
||||
|
||||
@@ -14,30 +14,30 @@ from graph_adjacency_list import GraphAdjList
|
||||
|
||||
def dfs(graph: GraphAdjList, visited: set[Vertex], res: list[Vertex], vet: Vertex):
|
||||
"""Depth-first traversal helper function"""
|
||||
res.append(vet) # Record visited vertex
|
||||
res.append(vet) # Record the visited vertex
|
||||
visited.add(vet) # Mark this vertex as visited
|
||||
# Traverse all adjacent vertices of this vertex
|
||||
# Traverse all neighbors of this vertex
|
||||
for adjVet in graph.adj_list[vet]:
|
||||
if adjVet in visited:
|
||||
continue # Skip vertices that have been visited
|
||||
# Recursively visit adjacent vertices
|
||||
continue # Skip vertices that have already been visited
|
||||
# Recursively visit the neighboring vertex
|
||||
dfs(graph, visited, res, adjVet)
|
||||
|
||||
|
||||
def graph_dfs(graph: GraphAdjList, start_vet: Vertex) -> list[Vertex]:
|
||||
"""Depth-first traversal"""
|
||||
# Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
# Represent the graph with an adjacency list to access all neighbors of a given vertex
|
||||
# Vertex traversal sequence
|
||||
res = []
|
||||
# Hash set for recording vertices that have been visited
|
||||
# Hash set recording visited vertices
|
||||
visited = set[Vertex]()
|
||||
dfs(graph, visited, res, start_vet)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
"""Driver code"""
|
||||
if __name__ == "__main__":
|
||||
# Initialize undirected graph
|
||||
# Initialize the undirected graph
|
||||
v = vals_to_vets([0, 1, 2, 3, 4, 5, 6])
|
||||
edges = [
|
||||
[v[0], v[1]],
|
||||
@@ -48,10 +48,10 @@ if __name__ == "__main__":
|
||||
[v[5], v[6]],
|
||||
]
|
||||
graph = GraphAdjList(edges)
|
||||
print("\nAfter initialization, the graph is")
|
||||
print("\nGraph after initialization:")
|
||||
graph.print()
|
||||
|
||||
# Depth-first traversal
|
||||
res = graph_dfs(graph, v[0])
|
||||
print("\nDepth-first traversal (DFS) vertex sequence is")
|
||||
print("\nVertex sequence from depth-first traversal (DFS):")
|
||||
print(vets_to_vals(res))
|
||||
|
||||
Reference in New Issue
Block a user