#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Graph {
int numVertices;
Node* adjacencyList[MAX_VERTICES];
int visited[MAX_VERTICES];
} Graph;
typedef struct Stack {
int data[MAX_VERTICES];
int top;
} Stack;
void initializeGraph(Graph* graph, int numVertices) {
graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
graph->adjacencyList[i] = NULL;
graph->visited[i] = 0;
}
}
void addEdge(Graph* graph, int src, int dest) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = dest;
newNode->next = graph->adjacencyList[src];
graph->adjacencyList[src] = newNode;
}
void dfsNonRecursive(Graph* graph, int startVertex) {
Stack stack;
stack.top = -1;
stack.data[++stack.top] = startVertex;
graph->visited[startVertex] = 1;
while (stack.top >= 0) {
int currentVertex = stack.data[stack.top--];
printf("Visited: %d\n", currentVertex);
Node* temp = graph->adjacencyList[currentVertex];
while (temp != NULL) {
int adjVertex = temp->data;
if (graph->visited[adjVertex] == 0) {
stack.data[++stack.top] = adjVertex;
graph->visited[adjVertex] = 1;
}
temp = temp->next;
}
}
}
int main() {
Graph graph;
int numVertices = 6;
initializeGraph(&graph, numVertices);
addEdge(&graph, 0, 1);
addEdge(&graph, 0, 2);
addEdge(&graph, 1, 3);
addEdge(&graph, 1, 4);
addEdge(&graph, 2, 5);
addEdge(&graph, 3, 5);
dfsNonRecursive(&graph, 0);
return 0;
}
编译执行
cc a.c
./a.out
多谢评论区的朋友指出错误.
记于2021年12月3日:
再次感谢黑河岛、'Best Wishes、yinwu_、萧瑟1