[Python] 욕심 알고리즘 - prim - 과 - Kruskal 구현 - 최소 생 성 트 리
연결 망 의 모든 생 성 트 리 에서 모든 변 의 대가 와 가장 작은 생 성 트 리 를 찾 아 최소 생 성 트 리 문제 라 고 부른다. (간단하게 말 하면 AOV 망 에서 n 개의 정점 대 가 를 연결 하 는 총 과 가장 작은 변 집 을 찾 는 것 이다.)
최소 생 성 트 리 의 두 가지 알고리즘, Prim 과 Kruskal 을 기록 합 니 다.
Prim 알고리즘 사고방식
Prim 알고리즘 코드
def cmp(key1, key2):
return (key1, key2) if key1 < key2 else (key2, key1)
def prim(graph, init_node):
visited = {init_node}
candidate = set(graph.keys())
candidate.remove(init_node) # add all nodes into candidate set, except the start node
tree = []
while len(candidate) > 0:
edge_dict = dict()
for node in visited: # find all visited nodes
for connected_node, weight in graph[node].items(): # find those were connected
if connected_node in candidate:
edge_dict[cmp(connected_node, node)] = weight
edge, cost = sorted(edge_dict.items(), key=lambda kv: kv[1])[0] # find the minimum cost edge
tree.append(edge)
visited.add(edge[0]) # cause you dont know which node will be put in the first place
visited.add(edge[1])
candidate.discard(edge[0]) # same reason. discard wont raise an exception.
candidate.discard(edge[1])
return tree
if __name__ == '__main__':
graph_dict = {
"A": {"B": 7, "D": 5},
"B": {"A": 7, "C": 8, "D": 9, "E": 5},
"C": {"B": 8, "E": 5},
"D": {"A": 5, "B": 9, "E": 15, "F": 6},
"E": {"B": 7, "C": 5, "D": 15, "F": 8, "G": 9},
"F": {"D": 6, "E": 8, "G": 11},
"G": {"E": 9, "F": 11}
}
path = prim(graph_dict, "D")
print(path) # [('A', 'D'), ('D', 'F'), ('A', 'B'), ('B', 'E'), ('C', 'E'), ('E', 'G')]
Prim 알고리즘 이 그림 에 주목 하 는 점 과 달리 Kruskal 알고리즘 은 그림 의 가장자리 에 더 관심 을 가 집 니 다.
Kruskal 알고리즘 사고방식
Kruskal 알고리즘 코드
def cmp(key1, key2):
return (key1, key2) if key1 < key2 else (key2, key1)
def find_parent(record, node):
if record[node] != node:
record[node] = find_parent(record, record[node])
return record[node]
def naive_union(record, edge):
u, v = find_parent(record, edge[0]), find_parent(record, edge[1])
record[u] = v
def kruskal(graph, init_node):
edge_dict = {}
for node in graph.keys():
edge_dict.update({cmp(node, k): v for k, v in graph[node].items()})
sorted_edge = list(sorted(edge_dict.items(), key=lambda kv: kv[1]))
tree = []
connected_records = {key: key for key in graph.keys()}
for edge_pair, _ in sorted_edge:
if find_parent(connected_records, edge_pair[0]) != \
find_parent(connected_records, edge_pair[1]):
tree.append(edge_pair)
naive_union(connected_records, edge_pair)
return tree
if __name__ == '__main__':
graph_dict = {
"A": {"B": 7, "D": 5},
"B": {"A": 7, "C": 8, "D": 9, "E": 5},
"C": {"B": 8, "E": 5},
"D": {"A": 5, "B": 9, "E": 15, "F": 6},
"E": {"B": 7, "C": 5, "D": 15, "F": 8, "G": 9},
"F": {"D": 6, "E": 8, "G": 11},
"G": {"E": 9, "F": 11}
}
path = kruskal(graph_dict, "D")
print(path) # [('A', 'D'), ('D', 'F'), ('A', 'B'), ('B', 'E'), ('C', 'E'), ('E', 'G')]
참고 문장
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
면접 에서 자바 SE 와 관련 된 몇 가지 큰 문제인터페이스 라 는 것 은 바로 시스템 류 (구조) 디자인 에 대한 고려 를 바탕 으로 하 는 것 이다.시스템 은 보통 여러 모듈 을 설계 해 야 한다. 여러 모듈 간 의 결합 관 계 는 보통 인터페이스 로 연결 되 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.