基于贪心算法实现tsp问题,通过python实现
时间: 2024-05-26 15:05:31 浏览: 145
下面是一个基于贪心算法的TSP问题的Python实现示例:
```python
import sys
def tsp(matrix):
n = len(matrix)
visited = [False] * n
visited[0] = True
path = [0]
total_distance = 0
for i in range(n-1):
min_distance = sys.maxsize
next_city = None
current_city = path[-1]
for j in range(n):
if not visited[j] and matrix[current_city][j] < min_distance:
min_distance = matrix[current_city][j]
next_city = j
visited[next_city] = True
path.append(next_city)
total_distance += min_distance
return path, total_distance
if __name__ == "__main__":
matrix = [
[0, 10, 15, 20],
[10, 0, 35, 25],
[15, 35, 0, 30],
[20, 25, 30, 0]
]
path, total_distance = tsp(matrix)
print(f"Path: {path}")
print(f"Total Distance: {total_distance}")
```
该算法的思路是从任意一个城市开始,每次选择距离最近的未访问过的城市,直到所有城市都被访问过。最后返回路径和总距离。
运行结果:
```
Path: [0, 1, 3, 2]
Total Distance: 80
```
该算法的时间复杂度是 $O(n^2)$,其中 $n$ 是城市数量。
阅读全文