Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add spanning tree #135

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

add spanning tree #135

wants to merge 4 commits into from

Conversation

weilycoder
Copy link
Contributor

@weilycoder weilycoder commented Oct 3, 2024

加入生成树,返回格式为(父,子)元组的列表

默认是从 1 开始执行 DFS(BFS 风格),可以通过指定容器实现 BFS 生成树或最小生成树。

可以通过传入 from_weight 决定是否显示边权和如何显示,默认是 lambda w: None,即不显示。

import random
import heapq
import collections
from cyaron.graph import *

random.seed(0, 2)


class Queue:
    def __init__(self):
        self.queue = collections.deque()

    def append(self, _x):
        self.queue.append(_x)

    def pop(self):
        return self.queue.popleft()

    def __bool__(self):
        return bool(self.queue)


class Heap:
    def __init__(self):
        self.heap = []

    def append(self, _x):
        heapq.heappush(self.heap, _x)

    def pop(self):
        return heapq.heappop(self.heap)

    def __bool__(self):
        return bool(self.heap)


g = Graph.graph(6, 10, weight_limit=10)
print(g.to_str())
print(g.to_tree()) # DFS 生成树
print(g.to_tree(5)) # DFS 生成树, 以 5 为根
print(g.to_tree(container=Queue)) # BFS 生成树
print(g.to_tree(container=Heap)) # 最小生成树

应该输出:

1 2 10
1 6 6
2 5 5
2 3 2
3 5 8
3 4 8
3 5 4
3 5 10
4 4 1
4 5 2
[(1, 6), (1, 2), (2, 3), (3, 5), (5, 4)]
[(5, 4), (4, 3), (3, 2), (2, 1), (1, 6)]
[(1, 2), (1, 6), (2, 5), (2, 3), (5, 4)]
[(1, 6), (1, 2), (2, 3), (3, 5), (5, 4)]
[(1, 6, 6), (1, 2, 10), (2, 3, 2), (3, 5, 4), (5, 4, 2)]

@weilycoder
Copy link
Contributor Author

解决了 #91 的问题。生成一棵树(或任意图),选一个点作为根节点即可。

Copy link
Collaborator

@Mr-Python-in-China Mr-Python-in-China left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

去写test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

请问如何生成一棵有根树,并以父->子的形式输出
2 participants