#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct Graph {
int vexnum;
int arcnum;
char* vexs;
int** arcs;
}Graph;
typedef struct Node {
int data;
struct Node* next;
}Node;
typedef struct Queue {
Node* front;
Node* rear;
}Queue;
void initQueue(Queue* queue) {
Node* headNode = (Node*)malloc(sizeof(Node));
headNode->next = NULL;
headNode->data = NULL;
queue->front = queue->rear = headNode;
}
void enQueue(Queue* queue, int element) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = element;
newNode->next = NULL;
queue->rear->next = newNode;
queue->rear = newNode;
}
int deQueue(Queue* queue) {
Node* temp = queue->front->next;
int index = temp->data;
queue->front->next = temp->next;
if (temp == queue->rear)
{
queue->rear = queue->front;
}
free(temp);
return index;
}
bool emptyQueue(Queue* queue) {
if (queue->front == queue->rear)
{
return true;
}
else
{
return false;
}
}
//图的初始化操作
Graph* initGraph(int vexnum) {
Graph* graph = (Graph*)malloc(sizeof(Graph));
graph->vexs = (char*)malloc(sizeof(char) * vexnum);
graph->arcs = (int**)malloc(sizeof(int*) * vexnum);
for (int i = 0; i < vexnum; i++)
{
graph->arcs[i] = (int*)malloc(sizeof(int)* vexnum);
}
graph->vexnum = vexnum;
graph->arcnum = 0;
return graph;
}
void createGraph(Graph* graph,char* vexs,int* arcs) {
for (int i = 0; i < graph->vexnum; i++)
{
graph->vexs[i] = vexs[i];
for (int j = 0; j < graph->vexnum; j++)
{
graph->arcs[i][j] = *(arcs + i * graph->vexnum + j);
if (graph->arcs[i][j] != 0)
{
graph->arcnum++;
}
}
}
graph->arcnum = graph->arcnum / 2;
printf("图创建成功!\n");
}
void DFS(Graph* graph, int* visited, int index) {
printf("%c ", graph->vexs[index]);
visited[index] = 1;
for (int i = 0; i < graph->vexnum; i++)
{
if (graph->arcs[index][i] == 1 && visited[i] == 0) {
DFS(graph, visited, i);
}
}
}
void BFS(Graph* graph, int* visited, int index) {
Queue queue;
initQueue(&queue);
printf("%c ", graph->vexs[index]);
visited[index] = 1;
enQueue(&queue, index);
while (!emptyQueue(&queue)) {
int i = deQueue(&queue);
for (int j = 0; j < graph->vexnum; j++)
{
if (graph->arcs[i][j] == 1 && visited[j] != 1)
{
printf("%c ", graph->vexs[j]);
visited[j] = 1;
enQueue(&queue, j);
}
}
}
}
int main() {
Graph* graph = initGraph(5);
int arcs[5][5] = {
0,1,1,1,0,
1,0,1,1,1,
1,1,0,0,0,
1,1,0,0,1,
0,1,0,1,0
};
int* visited = (int*)malloc(sizeof(int) * graph->vexnum);
for (int i = 0; i < graph->vexnum; i++)
{
visited[i] = 0;
}
char vexs[5] = { 'A','B','C','D','E' };
createGraph(graph, vexs, (int*)arcs);
printf("深度优先遍历序列:\n");
DFS(graph, visited, 0);
printf("\n");
for (int i = 0; i < graph->vexnum; i++)
{
visited[i] = 0;
}
printf("广度优先遍历序列:\n");
BFS(graph, visited, 0);
}