- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试解决一个程序,其中我必须找到给定路线列表连接的最大城市数。
例如: 如果给定的路线是 [['1', '2'], ['2', '4'], ['1', '11'], ['4', '11']]
那么连接的最大城市数将为 4
限制是我不能访问我已经访问过的城市。
我需要想法,比如如何进步。
目前,我的想法是,如果我能够创建一个字典,以城市为键,并将它连接到多少个其他城市作为其值,我就会接近解决方案(我希望如此)。例如:我的字典将是 {'1': ['2', '11'], '4': ['11'], '2': ['4']}
对于上面给定的输入。如果我遗漏了任何内容,我希望获得进一步的帮助和指导。
最佳答案
您可以使用 defaultdict
从边/路径列表中创建“图形”:
edges = [['1', '2'], ['2', '4'], ['1', '11'], ['4', '11']]
G = defaultdict(list)
for (s,t) in edges:
G[s].append(t)
G[t].append(s)
print G.items()
输出:
[ ('1', ['2', '11']), ('11', ['1', '4']), ('2', ['1', '4']), ('4', ['2', '11'])]
Note that I added the edges in both directions, since you're working with an undirected graph. So with the edge (a,b), G[a]
will include b
and G[b]
will include a
.
From this, you can use an algorithm like depth-first search or breadth-first search to discover all the paths in the graph.
In the following code, I used DFS:
def DFS(G,v,seen=None,path=None):
if seen is None: seen = []
if path is None: path = [v]
seen.append(v)
paths = []
for t in G[v]:
if t not in seen:
t_path = path + [t]
paths.append(tuple(t_path))
paths.extend(DFS(G, t, seen[:], t_path))
return paths
您可以使用:
G = defaultdict(list)
for (s,t) in edges:
G[s].append(t)
G[t].append(s)
print DFS(G, '1')
输出:
[('1', '2'), ('1', '2', '4'), ('1', '2', '4', '11'), ('1', '11'), ('1', '11', '4'), ('1', '11', '4', '2')]
So the full code, with the final bit that shows the longest path:
from collections import defaultdict
def DFS(G,v,seen=None,path=None):
if seen is None: seen = []
if path is None: path = [v]
seen.append(v)
paths = []
for t in G[v]:
if t not in seen:
t_path = path + [t]
paths.append(tuple(t_path))
paths.extend(DFS(G, t, seen[:], t_path))
return paths
# Define graph by edges
edges = [['1', '2'], ['2', '4'], ['1', '11'], ['4', '11']]
# Build graph dictionary
G = defaultdict(list)
for (s,t) in edges:
G[s].append(t)
G[t].append(s)
# Run DFS, compute metrics
all_paths = DFS(G, '1')
max_len = max(len(p) for p in all_paths)
max_paths = [p for p in all_paths if len(p) == max_len]
# Output
print("All Paths:")
print(all_paths)
print("Longest Paths:")
for p in max_paths: print(" ", p)
print("Longest Path Length:")
print(max_len)
输出:
All Paths: [('1', '2'), ('1', '2', '4'), ('1', '2', '4', '11'), ('1', '11'), ('1', '11', '4'), ('1', '11', '4', '2')]Longest Paths: ('1', '2', '4', '11') ('1', '11', '4', '2')Longest Path Length: 4
Note, the "starting point" of your search is specified by the second argument to the DFS
function, in this case, it's '1'
.
Update: As discussed in the comments the above code assumes you have a starting point in mind (specifically the code uses the node labelled '1'
).
A more general method, in the case that you have no such starting point, would be to perform the search starting at every node, and take the overall longest. (Note: In reality, you could be smarter than this)
Changing the line
all_paths = DFS(G, '1')
到
all_paths = [p for ps in [DFS(G, n) for n in set(G)] for p in ps]
会给你任何两点之间的最长路径。
(这是一个愚蠢的列表理解,但它允许我只更新一行。更清楚地说,它等同于以下内容:
all_paths = []
for node in set(G.keys()):
for path in DFS(G, node):
all_paths.append(path)
或
from itertools import chain
all_paths = list(chain.from_iterable(DFS(G, n) for n in set(G)))
).
关于python - 在图中找到最长的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29320556/
这个问题在这里已经有了答案: Different ways of loading a file as an InputStream (6 个答案) 关闭 8 年前。 在我的 gradle java
给定一个 User 类: class User end 我想使用 .class_eval 定义一个新常量.所以: User.class_eval { AVOCADO = 'fruit' } 如果我尝试
这可能听起来很奇怪,但我正在开发一个需要查找 div 内的元素或 div 本身的插件。 脚本根据用户选择查找元素,但内容(包括标记)是可变的。因此脚本将按如下方式查找元素: $('.block').f
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 7 年前。 Improve th
我需要在按我自己的函数排序的对的多集中查找并删除一个值。显然, .find 总是将迭代器返回到末尾,而不是返回到搜索到的值。有小费吗?这是函数: struct cmp { bool operato
求助!我将如何通过遍历查看字符并计算有效字符出现之前的下划线数量来查找和删除前导下划线。以及从字符串末尾向后迭代以查找任何尾随下划线。 我可以使用下面的方法来删除下划线,但是如何迭代才能找到下划线。
如果你在 $(xml) 中有下面的 xml,你会变得懒惰: $(xml).find("animal").find("dog").find("beagle").text() 在 jQuery 中是否有类
你如何找到4个文件的交集? 我用了grep -Fx -f 1.txt 2.txt 3.txt 4.txt ,但它似乎只适用于 2 个文件。同样comm -12 1.txt 2.txt无法扩展为 4 个
我已经完成了标记的姿势估计并获得了 rvec 和 tvec 值。我不知道如何找到它的中心,因为我需要绘制一个需要中心值的圆柱体。 我该怎么做? 最佳答案 标记的 tvec 是标记从原点的平移 (x,y
我有一个任务,我需要找到 2 个单链接(单对单)列表的交集。我还必须为 2 个双向链接(双重 vs 双重)列表执行此操作: 对于单链表,我使用 mergeSort() 对两个列表进行排序,然后逐项比较
我是 R 的新手,我有一个 100x100 的方阵。我想找到这个矩阵的最大特征值。我试过了 is.indefinite(x) 但是它写 is.indefinite(x) : argument x is
您好,我是 svg 和 JavaScript 的新手,当鼠标位于 svg 上方时,我试图使一些 svg 元素弹出(通过缩放),反之亦然,当鼠标离开 svg 元素时。 我已经能够通过使用转换使 svg
我正在尝试为 scala 项目编写一个类,但在多个地方使用 class、def、while 等关键字出现此错误。 它发生在这样的地方: var continue = true while (conti
我有两个 pandas 数据框,它们只取自一列并将日期列设置为索引,所以现在我有两个 Series。我需要找到这些系列的相关性。 这里有几行来自dfd: index change 2018-
我正在尝试调整我的 Vagrantfile,因此如果它丢失,它会自动在项目根目录中创建一个文件夹。创建文件夹没问题,但我无法找到创建该文件夹的位置。 我发现此信息可在 Vagrant::Environ
我正在尝试在 jquery 中找到 Test3 的位置,请有人引导我走上正确的道路。 我需要jquery来显示5 Test7 Test2 Test6 Test5 Test3 Test8 谢谢 最佳
大家早上好 我有一个像这样的图像列表: 使用 jQuery 如何查找 ul#preload 中包含特定字符串(例如“green”)的所有图像 src 类似... var new_src = j
我正在开发一个修改 Excel 文件的应用程序。 如何找到任意行中最后使用的单元格? 示例:行号 => 5 中最后使用的单元格 最佳答案 要找到一行中的最后一个单元格,您需要 Range 的 End
我刚刚陷入 react native ,需要一些帮助才能在找到 token 时导航到 protected 屏幕。我应该在哪里寻找应用程序加载时的 token ?如何在不多次调用导航的情况下导航用户一次
非常奇怪...此页面是 protected 内容还是我不知道的内容?我尝试单击下一页 anchor 。 参见this page first. 我试图用这个来抓取元素 var buttonNext =
我是一名优秀的程序员,十分优秀!