将x,y转换为图

发布于 2025-02-06 12:38:52 字数 179 浏览 4 评论 0原文

我有一个坐标的元组[0,1],[1,2],[1,3],[2,4],[4,5],[3,4]和我想将这些坐标转换为用于BFS中使用的图表,以便每个顶点都保留其邻居的列表。

所以这样的事情

0 = [1] 
1 = [0, 2, 3]
2 = [1, 4]

I've a tuple of coordinates [0, 1], [1, 2], [1, 3], [2, 4], [4, 5], [3, 4] and I want to convert these coordinates into a graph to be used in BFS so each vertex holds a list of its neighbor.

So something like this,

0 = [1] 
1 = [0, 2, 3]
2 = [1, 4]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜心小果奶 2025-02-13 12:38:53

快速而肮脏:

def append_to(out_dict, x, y):
    if x not in out_dict:
        out_dict[x] = []
    if y not in out_dict[x]:
        out_dict[x].append(y)

inpts = [[0, 1], [1, 2], [1, 3], [2, 4], [4, 5], [3, 4]]
out = {}
for inpt in inpts:
    append_to(out, inpt[0], inpt[1])
    append_to(out, inpt[1], inpt[0])

Quick and dirty:

def append_to(out_dict, x, y):
    if x not in out_dict:
        out_dict[x] = []
    if y not in out_dict[x]:
        out_dict[x].append(y)

inpts = [[0, 1], [1, 2], [1, 3], [2, 4], [4, 5], [3, 4]]
out = {}
for inpt in inpts:
    append_to(out, inpt[0], inpt[1])
    append_to(out, inpt[1], inpt[0])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文