【问题标题】:Depth First Search Adjacency深度优先搜索邻接
【发布时间】:2017-05-13 03:11:08
【问题描述】:

检查有向图是否强连接的程序

我有一个默认字典:

defaultdict(<class 'dict'>, {'SanFrancisco': {'Houston': '1000'},
 'LA': {'Ames': '300', 'SanFrancisco': True, 'Detroit': '200'}, 
'NYC': {'LA': '3000'}, 'Austin': {'Houston': '500'}}) 
# myDefaultDict = collections.defaultdict(dict)

还有一个包含所有不同字符串的集合:

{'Austin', 'LA', 'NYC', 'Ames', 'Detroit', 'Houston', 'SanFrancisco'}
# myNewSet

现在这是我的代码:

for i in myNewSet:
    break
    graph_DFT(i)

def graph_DFT(start):
    functionSet = set()
    myStack = []
    myStack.append(start)
    if not myStack:
        node = myStack.pop()
        # for neighbor in node's adjacent node
            #  if neighbor not visited - i.e. not in functionSet
                  # functionSet.add(neighbor)
                  # myStack.append(neighbor)

注意:我的 defaultdict 可以包含带有可选边权重的定向字符串。

那么如何检查相邻节点?老实说,在我的示例中,我不确定 100% 的相邻节点是什么。嵌套让我感到困惑。感谢您的帮助!

【问题讨论】:

  • 首先解释你认为相邻节点是什么。我们将从那里出发。
  • @aryamccarthy 是原点指向的任何节点吗?
  • 好。让我们在聊天中继续。 chat.stackoverflow.com/rooms/144105/…
  • 很高兴我能帮上忙。

标签: python dictionary search graph


【解决方案1】:

不说太多,我来解释一下。

你可以像这样遍历字典的键:

for k in mydict:
    ...

在你的例子中:

for neighbor in G[node]: # Assumes your defaultdict is `G`.
    ...

由于键是相邻节点,因此您可以对它们进行操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多