Итак, алгоритм моего прайма работает отлично, но я не могу понять, как реализовать на нем алгоритм Крускала. Куда я иду не так? Я добавил входной файл в конце. Спасибо!
import sys
class Graph:
def __init__(self,L):
self.number = int(L.pop(0))
self.nodes = [[float("inf") for x in range(self.number)] for y in range(self.number)]
self.weight = []
for line in L:
elements = list(line.split())
if len(elements) < 3:
pass
else:
self.nodes[int(elements[0])][int(elements[1])] = float(elements[2])
self.nodes[int(elements[1])][int(elements[0])] = float(elements[2])
self.nodes[int(elements[0])][int(elements[0])] = 0
# print(self.nodes)
def Kruskal(G):
print("Running Kruskal's Algorithm")
ans_list = []
no = []
i = 0
checkset = set()
for s in range(0,G.number):
checkset.add(s)
for r in G.nodes: # individual adjacency lists
print("The list is {} and the list number is {}".format(r,i)) # check
m = min(i for i in r if i if (i > 0 and not i in ans_list)) # least in list
if i < m:
no.append((r.index(m),i))
else:
no.append((i,r.index(m)))
ans_list.append(m)
i += 1
print(ans_list)
def prim(G,start_node):
T = set()
U = {start_node}
V = set()
for i in range(0,G.number):
V.add(i)
print("Starting Node: {}".format(start_node))
while U != V:
set_min = float("inf")
for i in (U):
for s in (V-U):
if G.nodes[i][s] < set_min:
set_min = G.nodes[i][s]
u = i
v = s
lowestWeight = {u,v}
print("Added",v)
print("Using Edge [{}, {}, {}]".format(str(min(lowestWeight)), str(max(lowestWeight)), G.nodes[u][v]))
T = T.union(lowestWeight)
U = U.union({v})
# no += 1
# for i in r:
# if i == 0:
# r[r.index(i)] = float("inf")
# else:
# mymin = min([min(r) for r in G.nodes])
# print("the minimum is ",mymin)
# break
if __name__ == "__main__":
print("Welcome to Minimum Spanning Tree Finder")
# fname = input("Give the file name graph is in:\n")
s = "Commands: \nexit or ctrl-d - quits the program\nhelp - prints this menu\nprim integer_value - run's Prim's algorithm starting at node given\nkruskal - runs Kruskal's algorithm"
# try:
# f = open(fname, "r")
# L = f.read().splitlines()
# except OSError:
# print ("Could not open/read file:", fname)
# sys.exit()
f = open("1.txt", "r")
L = f.read().splitlines()
print(s)
Graphs = Graph(L)
# print(L)
while True:
command = input("Enter command:\n")
if command == "exit":
print('Bye')
break
elif command == "help":
print(s)
elif command == "kruskal":
Kruskal(Graphs)
elif command[0:4] == "prim":
print("Running Prim's Algorithm")
prim(Graphs,int(command[5]))
else:
print("Unknown Command")
И входной файл, который я сейчас использую (первое число, 6 - это количество узлов, а вторая строка - первое число (0) - это узел, 3 - следующий узел, 5 - это вес. И далее
6
0 3 5
3 5 2
5 4 10
4 1 3
1 0 8
0 2 1
2 3 6
2 5 4
2 4 9
2 1 7