#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 100
typedef struct Node {
int vertex;
struct Node* next;
} Node;
typedef struct {
Node* head;
} AdjList[MAX_VERTICES];
void addEdge(AdjList adjList, int src, int dest) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = dest;
newNode->next = adjList[src].head;
adjList[src].head = newNode;
}
void printAllPathsUtil(AdjList adjList, int u, int v, int visited[], int path[], int pathIndex) {
visited[u] = 1;
path[pathIndex] = u;
pathIndex++;
if (u == v) {
for (int i = 0; i < pathIndex - 1; i++) {
printf("%d -> ", path[ i]);
}
printf("%d\n", path[pathIndex - 1]);
} else {
Node* current = adjList[u].head;
while (current != NULL) {
if (!visited[current->vertex]) {
printAllPathsUtil(adjList, current->vertex, v, visited, path, pathIndex);
}
current = current->next;
}
}
visited[u] = 0;
pathIndex--;
}
void printAllPaths(AdjList adjList, int u, int v, int numVertices) {
int visited[MAX_VERTICES] = {0};
int path[MAX_VERTICES];
int pathIndex = 0;
printAllPathsUtil(adjList, u, v, visited, path, pathIndex);
}
int main() {
int numVertices = 4;
AdjList adjList;
for (int i = 0; i < numVertices; i++) {
adjList[ i].head = NULL;
}
addEdge(adjList, 0, 1);
addEdge(adjList, 0, 2);
addEdge(adjList, 1, 2);
addEdge(adjList, 2, 0);
addEdge(adjList, 2, 3);
addEdge(adjList, 3, 3);
int u = 2, v = 3;
printf("从顶点%d到顶点%d的所有简单路径为:\n", u, v);
printAllPaths(adjList, u, v, numVertices);
return 0;
}