找到顶点x的距离d越来越小的顶点数

时间:2016-12-25 17:12:49

标签: c algorithm graph graph-traversal

我必须使用图遍历(我正在考虑BST)来确定g中的多少个顶点在v的距离中小于或等于N,这是一个距离为N的行程

int succN (Grafo g, int v, int N)

我有这个结构可以使用:

#define MAX 100

typedef int WEIGHT;

struct edge {
   int dest;
   WEIGHT weight;
   struct edge *next;
};

typedef struct edge Edge;
typedef struct edge *GraphL[MAX];

我很难在c中提供有效的解决方案。我现在看到的唯一方法是使用BST在辅助函数中进行递归调用

1 个答案:

答案 0 :(得分:1)

如果您的权重是非负的,则可以使用Dijkstra算法 这是一个简单的伪代码。它具有O(n^2)时间复杂度(n =节点数)。

ans = 0
dist[0 .. n-1, None] = {INF, ..., INF}
dist[v] = 0
iterate n times
   best = None

   for each node u
      if not seen[u] and dist[u] < dist[best]
         best = u

   if dist[best] > N
      break

   seen[best] = true
   ans++
   for each edge from best (going to v, of weight w)
      if dist[best] + w < dist[v]
         dist[v] = dist[best] + w

return ans

如果你的所有权重都等于1(正如你在评论中指出的那样),那么breadth-first search就足够了。

相关问题