我正在尝试在 C 中编写深度优先搜索。在搜索中,我不必维护一组所有可访问节点,而是必须将 Vertex 中的 isVisited 字段标记为 1 以表示已访问。这是我的数据结构和我的算法尝试。
struct Vertex {
char label;
int isVisited;
int numNeighbors;
struct Vertex** neighbors;
};
typedef struct Vertex Vertex;
struct Graph {
int numEdges;
int numVertices;
Vertex* vertexSet;
};
typedef struct Graph Graph;
struct DLink {
TYPE value;
struct DLink * next;
struct DLink * prev;
};
struct cirListDeque {
int size;
struct DLink *last;
};
typedef struct cirListDeque cirListDeque;
这是我对 DFS 实施的尝试:
int DFS(Graph* g, Vertex* source, Vertex* destination) {
cirListDeque stack;
TYPE currentVertex;
int i;
initCirListDeque(&stack);
addBackCirListDeque(&stack, source);
while(!isEmptyCirListDeque(&stack)) {
currentVertex = backCirListDeque(&stack);
removeBackCirListDeque(&stack);
if(currentVertex->label == destination->label) {
return 1;
}
else {
if(currentVertex->isVisited == 0) {
currentVertex->isVisited = 1;
for(i = 0; i < currentVertex->numNeighbors; i++) {
if(currentVertex->neighbors[i]->label == destination->label) {
return 1;
}
else {
addBackCirListDeque(&stack, currentVertex->neighbors[i]);
if(currentVertex->neighbors[i]->isVisited == 0) {
addBackCirListDeque(&stack, currentVertex->neighbors[i]);
}
}
}
}
}
}
return 0;
}
这个搜索的问题是它永远不会返回一个节点是可达的,即使它是可达的。有人知道我该如何纠正吗?