写一个完整的C语言的无向图并用BFS算法查找最短路径的代码
时间: 2023-05-19 15:05:43 浏览: 136
以下是一个完整的C语言无向图的实现,包括BFS算法查找最短路径的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_VERTICES 100
typedef struct {
int data[MAX_VERTICES];
int rear, front;
} Queue;
void initQueue(Queue *q) {
q->rear = -1;
q->front = -1;
}
bool isEmpty(Queue *q) {
return q->rear == q->front;
}
bool isFull(Queue *q) {
return q->rear == MAX_VERTICES - 1;
}
void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full\n");
return;
}
q->data[++q->rear] = value;
}
int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return -1;
}
return q->data[++q->front];
}
typedef struct {
int data[MAX_VERTICES];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
bool isStackEmpty(Stack *s) {
return s->top == -1;
}
bool isStackFull(Stack *s) {
return s->top == MAX_VERTICES - 1;
}
void push(Stack *s, int value) {
if (isStackFull(s)) {
printf("Stack is full\n");
return;
}
s->data[++s->top] = value;
}
int pop(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
return s->data[s->top--];
}
typedef struct {
int vertices[MAX_VERTICES];
int edges[MAX_VERTICES][MAX_VERTICES];
int vertexCount;
int edgeCount;
} Graph;
void initGraph(Graph *g) {
g->vertexCount = 0;
g->edgeCount = 0;
}
void addVertex(Graph *g, int value) {
g->vertices[g->vertexCount++] = value;
}
void addEdge(Graph *g, int start, int end) {
g->edges[start][end] = 1;
g->edges[end][start] = 1;
g->edgeCount++;
}
void printGraph(Graph *g) {
int i, j;
for (i = 0; i < g->vertexCount; i++) {
printf("%d: ", g->vertices[i]);
for (j = 0; j < g->vertexCount; j++) {
if (g->edges[i][j] == 1) {
printf("%d ", g->vertices[j]);
}
}
printf("\n");
}
}
void bfs(Graph *g, int startVertex, int endVertex) {
bool visited[MAX_VERTICES] = { false };
Queue q;
initQueue(&q);
visited[startVertex] = true;
enqueue(&q, startVertex);
while (!isEmpty(&q)) {
int currentVertex = dequeue(&q);
printf("%d ", g->vertices[currentVertex]);
if (currentVertex == endVertex) {
printf("\n");
return;
}
int i;
for (i = 0; i < g->vertexCount; i++) {
if (g->edges[currentVertex][i] == 1 && !visited[i]) {
visited[i] = true;
enqueue(&q, i);
}
}
}
}
int main() {
Graph g;
initGraph(&g);
addVertex(&g, 1);
addVertex(&g, 2);
addVertex(&g, 3);
addVertex(&g, 4);
addVertex(&g, 5);
addVertex(&g, 6);
addEdge(&g, 0, 1);
addEdge(&g, 0, 2);
addEdge(&g, 1, 3);
addEdge(&g, 1, 4);
addEdge(&g, 2, 4);
addEdge(&g, 3, 5);
addEdge(&g, 4, 5);
printf("Graph:\n");
printGraph(&g);
printf("BFS: ");
bfs(&g, 0, 5);
return 0;
}
```
这个程序实现了一个无向图,并使用BFS算法查找从起点到终点的最短路径。在这个例子中,我们使用了一个队列来实现BFS算法。
阅读全文