用c实现了图的部分操作(存储方式为邻接表,邻接矩阵请移步之前文章 :图的邻接矩阵实现c语言版)。
参考文献:Fundamentals of Data Structures in C
请看代码和注释:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#define MAX_VERTICES 10 //最大顶点数量
#define TRUE 1
#define FALSE 0
#define MAX_QUE 20 //队列长度,此处选用循环队列,所以最大容量应该是20-1 = 19
typedef struct node* node_pointer;//链表结构
typedef struct node{
int vertex;
node_pointer link;
};
short visited[MAX_VERTICES];//声明记录顶点是否访问过的数组,访问过则元素值为1,即TRUE
int rear = 0; //队列的尾
int front = 0;//队列的头
node_pointer graph[MAX_VERTICES];
typedef int element;
element que[MAX_QUE];
/*判断队列是否为空*/
int empty()
{
return rear == front;
}
/*对队列插入元素*/
void addq(int front, int *rear, element item)
{
*rear = (*rear+1)%MAX_QUE;
if(*rear == front)
return;
que[*rear] = item;
}
/*队列的删除操作*/
element delq(int *front, int rear)
{
if(empty())
printf("It's empty! \n");
*front = (*front+1)%MAX_QUE;
return que[*front];
}
/*图的生成
先输入一个顶点,然后输入和这个顶点相连的其他顶点,接着输入另一个顶点,类推*/
void input()
{
int i = 0;
int m, n;
node_pointer current;
for(; i < MAX_VERTICES; i++){
graph[i] = (node_pointer)malloc(sizeof(struct node));//free
graph[i]->link = NULL;/*init the graph*/
}
printf("输入图的边:\n");
while(1){
printf("输入顶点:(m的值为-1停止录入)\n");
scanf("%d",&m);
if(m == -1)
break;
current = graph[m];
current->vertex = m;
printf("输入另一个顶点:值为-1则表示m为独立顶点\n");
scanf("%d",&n);
while(n != -1){
node_pointer node = (node_pointer)malloc(sizeof(struct node));//free()
node->vertex = n;
node->link = NULL;
while(current->link)
current = current->link;
current->link = node;
scanf("%d",&n);
}
}
}
/*深度优先搜索*/
void dfs(int i)
{
node_pointer current;
visited[i] = TRUE;
printf("%5d",i);
for(current = graph[i]; current; current = current->link)
if(!visited[current->vertex])
dfs(current->vertex);
printf("\n");
}
/*广度优先*/
void bfs(int v)
{
int n ;
node_pointer w;
printf("%5d", v);
addq(front, &rear, v);
visited[v] = TRUE;
while(!empty()){
n = delq(&front, rear);
for(w = graph[n]; w; w = w->link)
if(!visited[w->vertex]){
visited[w->vertex] = TRUE;
printf("%5d", w->vertex);
addq(front, &rear, w->vertex);
}
}
printf("\n");
}
/*获得连通分支*/
void connected(int n)
{
int i = 0;
for(; i < n; i++){
if(!visited[i])
dfs(i);
printf("\n");
}
}
int main()
{
int i = 0;
int j = 0;
int n = 5;//顶点的数量
for(; j < MAX_VERTICES; j++)
visited[j] = FALSE;
input();
dfs(0);//dfs操作之后visited数组的元素值都为True,所以要进行初始化,后面的visited数组初始化操作类似。
for(j = 0; j < MAX_VERTICES; j++)
visited[j] = FALSE;
bfs(0);
for(j = 0; j < MAX_VERTICES; j++)
visited[j] = FALSE;
connected(n);
return 0;
}