# n: number of city # result: [] # distance: [][] defnext_city(n, result, distance): current_city = result[-1] min_distance = None next_city = None for x inrange(n): if x in result: continue if min_distance isNoneor distance[current_city][x] < min_distance: next_city = x min_distance = distance[current_city][x] return next_city
# 根据n,生成用于测试的距离矩阵 defget_distance_matrix(n): distance_matrix = [[0for x inrange(n)] for y inrange(n)] for i inrange(n): distance_matrix[i][i] = 0 for j inrange(i+1,n): distance = random.randint(10,99) distance_matrix[i][j] = distance distance_matrix[j][i] = distance print('from {0} to other cities: {1}'.format(i,distance_matrix[i])) return distance_matrix
# Test n = int(input('input number of cities: ')) distance_matrix = get_distance_matrix(n)
# 根据n,生成用于测试的距离矩阵 defget_distance_matrix(n): distance_matrix = [[0for x inrange(n)] for y inrange(n)] for i inrange(n): distance_matrix[i][i] = 0 for j inrange(i+1,n): distance = random.randint(10,99) distance_matrix[i][j] = distance distance_matrix[j][i] = distance print('from {0} to other cities: {1}'.format(i,distance_matrix[i])) return distance_matrix
# Test # n = int(input('input number of cities: ')) n = 5 m = 101
force_total = 0 greedy_total = 0
for i inrange(m): print('---> test #', i) distance_matrix = get_distance_matrix(n)