Algorithmensammlung: Graphentheorie: Algorithmus von Kruskal
Aus Wikibooks
Algorithmensammlung: Graphentheorie
-
- Algorithmus von Kruskal
- Algorithmus von Prim
- Breitensuche (BFS - breadth first search)
- Dijkstra-Algorithmus
- Tiefensuche (DFS - depth first search)
Algorithmus von Kruskal [Bearbeiten]
Der Algorithmus von Kruskal ist ein Algorithmus zum Auffinden minimaler Spannbäume in einem zusammenhängenden, ungerichteten, kantengewichteten Graphen.
Für nähere Informationen siehe
Algorithmus von Kruskal.
Python [Bearbeiten]
def kruskal(knoten, kanten): # knoten ist eine Liste von Knoten # kanten ist eine Liste von 3-Tupeln: # (knoten1, knoten2, kosten) # Gibt ein Tupel ( knoten, kanten ) im selben # Format zurück tKnoten = [ knoten[0] ] tKanten = [] zshgKomponenten = [] sortierteKanten = sorted(kanten, key=lambda x: x[2]) while len(tKnoten) != len(knoten): # Günstigste Kante nehmen kante = sortierteKanten.pop(0) # Die Kanten, die einen Kreis bilden würden, # entfernen. Dafür Zusammenhangskomponenten merken zshgKompA = filter(lambda x: kante[0] in x, zshgKomponenten) zshgKompB = filter(lambda x: kante[1] in x, zshgKomponenten) if zshgKompA and zshgKompB and zshgKompA == zshgKompB: continue elif zshgKompA and zshgKompB and zshgKompA != zshgKompB: zshgKompA += zshgKompB zshgKomponenten.remove(zshgKompB) elif zshgKompB: zshgKompB[0] += [ kante[0] ] elif zshgKompA: zshgKompA[0] += [ kante[1] ] else: zshgKomponenten += [ [ kante[0], kante[1] ] ] # Kante in Baum aufnehmen if kante[0] not in tKnoten: tKnoten += [ kante[0] ] if kante[1] not in tKnoten: tKnoten += [ kante[1] ] tKanten += [ kante ] # Zu Lernzwecken: # print zshgKomponenten return (tKnoten, tKanten) if __name__ == "__main__": print kruskal([1,2,3,4,5], [ (1,2,1), (2,3,5), (3,4,2), (4,5,1), (1,3,1) ])