生成无向图的bfs的c语言代码
时间: 2023-12-25 13:10:44 浏览: 68
以下是生成无向图的BFS的C语言代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int queue[MAX];
int front = -1, rear = -1;
void enqueue(int vertex)
{
if(rear == MAX - 1)
printf("Queue Overflow\n");
else
{
if(front == -1)
front = 0;
rear++;
queue[rear] = vertex;
}
}
int dequeue()
{
int delvertex;
if(front == -1 || front > rear)
{
printf("Queue Underflow\n");
return -1;
}
else
{
delvertex = queue[front];
front++;
return delvertex;
}
}
void BFS(int adj_matrix[][MAX], int visited[], int start, int n)
{
int i, vertex;
visited[start] = 1;
enqueue(start);
while (front != -1)
{
vertex = dequeue();
printf("%d ", vertex);
for(i = 0; i < n; i++)
{
if(adj_matrix[vertex][i] == 1 && visited[i] == 0)
{
visited[i] = 1;
enqueue(i);
}
}
}
}
int main()
{
int n, i, j, start;
int adj_matrix[MAX][MAX], visited[MAX];
printf("Enter the number of vertices in the graph: ");
scanf("%d", &n);
printf("\nEnter the adjacency matrix:\n");
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
scanf("%d", &adj_matrix[i][j]);
for(i = 0; i < n; i++)
visited[i] = 0;
printf("\nEnter the starting vertex: ");
scanf("%d", &start);
printf("\nBFS Traversal:\n");
BFS(adj_matrix, visited, start, n);
return 0;
}
阅读全文