一千萬個為什麽

搜索

將獲取附加到特定節點的所有節點的算法

我正在創建一個基於有向圖的算法。我想要一個能夠獲取連接到特定節點的所有節點的函數。

public List GetNodesInRange(Graph graph, int Range, Node selected)
{
    var result = new List();
    result.Add(selected);
    if (Range > 0)
    {
        foreach (Node neighbour in GetNeighbours(graph, selected))
        {
            result.AddRange(GetNodesInRange(graph, Range - 1, neighbour));
        }
    }
    return result;
}

private List GetNeighbours(Graph graph, Node selected)
{
    foreach(Node node in graph.node)
    {
        if (node == selected)
        {
            GetNodesInRange(node, Range-1, /*don't know what 2 do here*/);
            //and confused all the way down

最佳答案

這取決於您對圖表使用的實現方式:

  • edge list: you search all edges that have the specified vertex as first or second parameter to the edge
  • adjacency list: the list attached to a node is already the list of nodes incident to it
  • adjacency matrix: you take the column (or row) of the vertex that you chose

轉載註明原文: 將獲取附加到特定節點的所有節點的算法