Skip to content

Commit e39c3ce

Browse files
committed
Add TSP Problem
1 parent 10b1a2a commit e39c3ce

File tree

2 files changed

+13
-6
lines changed

2 files changed

+13
-6
lines changed

graphs/tests/test_traveling_salesman_problem.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,9 +28,10 @@ def test_greedy():
2828
graph = sample_graph_1()
2929
# The greedy algorithm does not guarantee an optimal solution;
3030
# it is necessary to verify that its output is an integer greater than 0.
31+
# An approximate solution cannot be represented by '==' and can only ensure that the result is reasonable.
3132
result = tsp_greedy(graph)
3233
assert isinstance(result, int)
33-
assert result > 0
34+
assert result >= 64
3435

3536
def test_dp_larger_graph():
3637
graph = sample_graph_2()
@@ -42,7 +43,6 @@ def test_brute_force_larger_graph():
4243

4344
def test_greedy_larger_graph():
4445
graph = sample_graph_2()
45-
# An approximate solution cannot be represented by '==' and can only ensure that the result is reasonable.
4646
result = tsp_greedy(graph)
4747
assert isinstance(result, int)
4848
assert result >= 80

graphs/traveling_salesman_problem.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ def tsp_greedy(graph: list[list[int]]) -> int:
8888
Example:
8989
>>> tsp_greedy([[0, 29, 20], [29, 0, 15], [20, 15, 0]])
9090
64
91+
>>> tsp_greedy([[0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0]])
92+
80
9193
"""
9294
n = len(graph)
9395
visited = [False] * n # Mark whether each city has been visited.
@@ -124,22 +126,27 @@ def tsp_greedy(graph: list[list[int]]) -> int:
124126

125127

126128
def test_tsp_example():
127-
graph = [[0, 29, 20], [29, 0, 15], [20, 15, 0]]
129+
graph = [
130+
[0, 10, 15, 20],
131+
[10, 0, 35, 25],
132+
[15, 35, 0, 30],
133+
[20, 25, 30, 0],
134+
]
128135

129136
result = tsp_brute_force(graph)
130-
if result != 64:
137+
if result != 80:
131138
raise Exception('tsp_brute_force Incorrect result')
132139
else:
133140
print('Test passed')
134141

135142
result = tsp_dp(graph)
136-
if result != 64:
143+
if result != 80:
137144
raise Exception('tsp_dp Incorrect result')
138145
else:
139146
print("Test passed")
140147

141148
result = tsp_greedy(graph)
142-
if result != 64:
149+
if result != 80:
143150
if result < 0:
144151
raise Exception('tsp_greedy Incorrect result')
145152
else:

0 commit comments

Comments
 (0)