我正在尝试编写一个函数int within(Graph g, Vertex s, int d, Vertex *vs)
。该函数需要Graph g, Vertex s (source vertex), int d (an upper bound on distance), a pointer to array of vertices Vertex *vs (note, Vertex is typedef int)
。该函数应该从源d
中找到距离小于或等于s
的所有顶点。它将所有这些顶点存储在vs[]
数组中,该数组作为指针传递给函数。该函数返回vs[]
中的元素数。
Examples of vertices that would be produced for various calls to the within() function:
问题
我已经实现了这个功能,如下所示。 ()调用的唯一函数是findPath(),它也如下所示。但是,出于某种原因,这里有一个无限循环:
for(v = i; v != s; v = path[v]){
count++; //HERE IS THE INFINITE LOOP
}
我在这里要做的是计算从源顶点到当前顶点(v)的边数。
在()函数中
// Find all vertices which are <= d edges from v
int within(Graph g, Vertex s, int d, Vertex *vs)
{
int i;
//distance from current vertex to source vertex
int distance = 0;
//index to count number of elements in vs[]
int vsIndex = 0;
//for each vertex in the graph
for(i=0; i<g->nV; i++){
//make sure current vertex is not the source vertex
if(i != s){
//find path from current vertex to source vertex
findPath(g, s, i);
//compute distance from current to source vertex
Vertex v;
for(v = i; v != s; v = path[v]){
count++; //HERE IS THE INFINITE LOOP
}
*/if distance from current to source is less than or equal to d,
add current vertex to vs[] array and increment vsIndex.
/*
if(count <= d){
vs[vsIndex++] = i;
}
//reset distance for next vertex to be checked
count = 0;
}
}
return vsIndex;
}
它是
的一部分的文件#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include "Graph.h"
#include "Queue.h"
#include "Stack.h"
// graph representation (adjacency matrix)
typedef struct GraphRep {
int nV; // #vertices
int nE; // #edges
int **edges; // matrix of booleans
} GraphRep;
// - these variables are used by various algorithms
static int *visited; // array [0//nV-1] of seen vertices
static int *path; // array [0..V-1] of vertices in path
void findPath(Graph g, Vertex src, Vertex dest)
{
int i;
// array of "been visited" flags
for (i = 0; i < g->nV; i++) visited[i] = 0;
// array of path predecessor vertices
Queue q = newQueue();
QueueJoin(q, src); visited[src] = 1;
int isFound = 0;
while (!QueueIsEmpty(q) && !isFound) {
Vertex y, x = QueueLeave(q);
for (y = 0; y < g->nV; y++) {
if (!g->edges[x][y]) continue;
path[y] = x;
if (y == dest) { isFound = 1; break; }
if (!visited[y]) {
QueueJoin(q, y);
visited[y] = 1;
}
}
}
}