【问题标题】:Check if all nodes in graph are in distance of <=k from each other检查图中的所有节点是否彼此之间的距离 <=k
【发布时间】:2019-10-12 00:32:13
【问题描述】:

在给定的图中,我需要检查图中的所有节点是否彼此之间的距离为

我写了一个解决方案(简单的 C#),在每个节点上运行一个循环,然后检查他到所有其他节点是否有 k 距离,但时间复杂度是 V * (V + E)。 有没有更高效的方法?

代码:

// node defenition
public class GraphNode
{
   public GraphNode(int data, List<GraphNode> neighbours)
   {
        Data = data;
       Neighbours = neighbours;
   }
}

// Loop on every Node, and find all k-distance neighbours
public bool IfAllGraphNodesInKdistance1(List<GraphNode> nodes, int k)
{
    for(int i=1; i< nodes.Count; i++)
    {
         if(FindKdistanceNeighboursInGraph(nodes[i], k).Count != nodes.Count)
                return false;
        }
        return true;
    }
}


// Find k-distance neighbours of a Node
public HashSet<GraphNode> FindKdistanceNeighboursInGraph(GraphNode node, int distance )
{

    HashSet<GraphNode> resultHash = new HashSet<GraphNode>();

    if (node != null && distance > 0)
    {
        HashSet<GraphNode> visited = new HashSet<GraphNode>();
        Queue<GraphNode> queue1 = new Queue<GraphNode>();
        Queue<GraphNode> queue2 = new Queue<GraphNode>();
        queue1.Enqueue(node);
        visited.Add(node);
        int currentDistance = 0;
        while (queue1.Count > 0 && currentDistance < distance)
        {
            GraphNode current = queue1.Dequeue();
            foreach (GraphNode graphNode in current.Neighbours)
            {
                if (!visited.Contains(graphNode))
                {
                    queue2.Enqueue(graphNode);
                    visited.Add(graphNode);
                    resultHash.Add(graphNode);
                }
            }
            if (queue1.Count == 0)
            {
                queue1 = queue2;
                queue2 = new Queue<GraphNode>();
                currentDistance++;
            }
        }
    }
    resultHash.Add(node); // if it will include current
    return resultHash;
}

【问题讨论】:

    标签: c# algorithm graph


    【解决方案1】:

    首先,你的算法实际上是 V * (V + E)。

    我不确定你是否可以在实践中变得更好。你绝对可以改进你的代码。

    有一些算法可以计算所有对的最短路径,例如 Floyd-Warshall。对于您的情况,最快的一种(无向无权图)称为 Seidel 算法。

    【讨论】:

      【解决方案2】:

      您可以从您的图表创建一个矩阵,然后在该矩阵中找到较低的值,当您尝试找到节点之间的较短路径或将某些算法应用于您的图表等时,它也很有用。

      Simple example of representing a graph as matrix

      【讨论】:

      • 找到较低的值是什么意思?
      • 抱歉,我没有注意到您试图找到 k 距离,而不是最小值。您可以在矩阵中找到您的距离,而不是找到最低值,然后只获取坐标,这将是您尝试找到的点和方式。
      • 我认为你假设有一个距离矩阵,但事实并非如此。计算这样一个矩阵不是免费的。
      • 另外,OP 不会寻找与其他节点有 k 距离的节点。 OP 想要一个答案是/否,是否所有节点之间的距离不超过 k。
      • 我说的是距离矩阵。是的,你是对的,计算不是免费的,但在最坏的情况下,矩阵的计算会更快,渐近复杂度将为 O(n^2 - n),对于有向图 O((n^2 - n) / 2),你也可以优化它(这取决于具体的任务)。关于第二条评论,OP 想知道的仅取决于您的明确任务(如何处理数组由您决定),我只是假设处理会更快。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2019-11-19
      相关资源
      最近更新 更多