【图的遍历与邻接表】

图的遍历与邻接表

图是由顶点与顶点之间的边组成的,图中的数据元素称为顶点,顶点之间的逻辑关系用边来表示
定义图的结构体:

typedef struct Graph {
    int** connections;
    int numNodes;
}*GraphPtr,Graph;

图的初始化:

GraphPtr initGraph(int parasize, int** paraData){
    int i,j;
    GraphPtr resultPtr = (GraphPtr)malloc(sizeof(Graph));
    resultPtr->numNodes = parasize;
    resultPtr->connections = (int**)malloc(sizeof(int*)*parasize);
    for(i = 0;i < parasize; i++){//将测试的数据传入
        resultPtr->connections[i] = (int*)malloc(sizeof(int)*parasize);
        for(j = 0; j <parasize; j++){
            resultPtr->connections[i][j] = paraData[i][j];
        }
    } 
    return resultPtr;
}

判断结点是否被访问过:

void initTranverse(GraphPtr paraGraphPtr){
    int i;
    visitedPtr = (int*)malloc(sizeof(int)*paraGraphPtr->numNodes);
    for(i = 0;i <paraGraphPtr->numNodes; i++){
        visitedPtr[i] = 0;//先初始化为0,全都没被访问过
    }
}

深度优先遍历,递归实现:

void depthFirstTranverse(GraphPtr paraGraphPtr, int paraNode){
    int i;
    
    visitedPtr[paraNode] = 1;
    printf("%d\t",paraNode);

    for(i = 0;i <paraGraphPtr->numNodes; i++){
        if(!visitedPtr[i]){
            if(paraGraphPtr->connections[paraNode][i]){
                depthFirstTranverse(paraGraphPtr, i);
            }
        }
    }
}

在进行图的广度优先遍历时使用队列实现:

void widthFirstTranverse(GraphPtr paraGraphPtr, int paraStart){
    int i, j, tempNode;
    QueuePtr tempQueuePtr = initQueue();
    printf("%d\t",paraStart);
    visitedPtr[paraStart] = 1;//访问过则赋值为1
    enqueue(tempQueuePtr, paraStart);
    while(!isQueueEmpty(tempQueuePtr)){//队列不为空就进行循环
        tempNode = dequeue(tempQueuePtr);
        visitedPtr[tempNode] = 1;
        i++;
        for(j = 0; j < paraGraphPtr->numNodes; j++){
            if(visitedPtr[j])//判断是否访问过
                continue;
            if(paraGraphPtr->connections[tempNode][j] == 0)
                continue;
            
            printf("%d\t",j);
            visitedPtr[j] = 1;
            enqueue(tempQueuePtr, j);
        }
    }
}

总代码:

#include<stdio.h>
#include<malloc.h>
#define QUEUE_SIZE 10
int* visitedPtr;
//定义队列的结构体
typedef struct GraphNodeQueue{
    int* nodes;
    int front;
    int rear;
}GraphNodeQueue,*QueuePtr;
//队列初始化
QueuePtr initQueue(){
    QueuePtr resultQueuePtr = (QueuePtr)malloc(sizeof(struct GraphNodeQueue));
    resultQueuePtr->nodes = (int*)malloc(QUEUE_SIZE*sizeof(int));
    resultQueuePtr->front = 0;
    resultQueuePtr->rear = 1;
    return resultQueuePtr;
}
//判断队列是否为空
int isQueueEmpty(QueuePtr paraQueuePtr){
    if((paraQueuePtr->front+1)%QUEUE_SIZE == paraQueuePtr->rear){
        return 1;
    }
    return 0;
}
//入队
void enqueue(QueuePtr paraQueuePtr, int paraNode){
    if((paraQueuePtr->rear+1)%QUEUE_SIZE ==paraQueuePtr->front%QUEUE_SIZE){
        printf("Error,tring to enqueue %d.queue full\r\n",paraNode);
    }
    paraQueuePtr->nodes[paraQueuePtr->rear] = paraNode;
    paraQueuePtr->rear = (paraQueuePtr->rear+1)%QUEUE_SIZE;
}
//出队
int dequeue(QueuePtr paraQueuePtr){
    if(isQueueEmpty(paraQueuePtr)){
        printf("Error, empty queue\r\n");
        return 0;
    }
    paraQueuePtr->front = (paraQueuePtr->front+1) % QUEUE_SIZE;
    return paraQueuePtr->nodes[paraQueuePtr->front];
}
//定义图的结构体
typedef struct Graph {
    int** connections;
    int numNodes;
}*GraphPtr,Graph;
//图的初始化
GraphPtr initGraph(int parasize, int** paraData){
    int i,j;
    GraphPtr resultPtr = (GraphPtr)malloc(sizeof(Graph));
    resultPtr->numNodes = parasize;
    resultPtr->connections = (int**)malloc(sizeof(int*)*parasize);
    for(i = 0;i < parasize; i++){//将测试的数据传入
        resultPtr->connections[i] = (int*)malloc(sizeof(int)*parasize);
        for(j = 0; j <parasize; j++){
            resultPtr->connections[i][j] = paraData[i][j];
        }
    } 
    return resultPtr;
}
//判断结点是否被访问过
void initTranverse(GraphPtr paraGraphPtr){
    int i;
    visitedPtr = (int*)malloc(sizeof(int)*paraGraphPtr->numNodes);
    for(i = 0;i <paraGraphPtr->numNodes; i++){
        visitedPtr[i] = 0;//先初始化为0,全都没被访问过
    }
}
// 深度优先遍历,递归实现
void depthFirstTranverse(GraphPtr paraGraphPtr, int paraNode){
    int i;
    
    visitedPtr[paraNode] = 1;
    printf("%d\t",paraNode);

    for(i = 0;i <paraGraphPtr->numNodes; i++){
        if(!visitedPtr[i]){
            if(paraGraphPtr->connections[paraNode][i]){
                depthFirstTranverse(paraGraphPtr, i);
            }
        }
    }
}
// 广度优先遍历,队列实现
void widthFirstTranverse(GraphPtr paraGraphPtr, int paraStart){
    int i, j, tempNode;
    QueuePtr tempQueuePtr = initQueue();
    printf("%d\t",paraStart);
    visitedPtr[paraStart] = 1;//访问过则赋值为1
    enqueue(tempQueuePtr, paraStart);
    while(!isQueueEmpty(tempQueuePtr)){//队列不为空就进行循环
        tempNode = dequeue(tempQueuePtr);
        visitedPtr[tempNode] = 1;
        i++;
        for(j = 0; j < paraGraphPtr->numNodes; j++){
            if(visitedPtr[j])//判断是否访问过
                continue;
            if(paraGraphPtr->connections[tempNode][j] == 0)
                continue;
            
            printf("%d\t",j);
            visitedPtr[j] = 1;
            enqueue(tempQueuePtr, j);
        }
    }
}
void testGraphTranverse(){
    int i,j;
    int** tempPtr;
    int myGraph[5][5] = { 
		{0, 1, 0, 1, 0},
		{1, 0, 1, 0, 1}, 
		{0, 1, 0, 1, 1}, 
		{1, 0, 1, 0, 0}, 
		{0, 1, 1, 0, 0}};
	printf("Preparing data\r\n");

    tempPtr=(int**)malloc(sizeof(int*)*5);
    for(i = 0; i < 5; i++){
        tempPtr[i] = (int*)malloc(sizeof(int)*5);
    }
    for(i = 0;i < 5; i++){
        for(j = 0; j< 5; j++){
            tempPtr[i][j] = myGraph[i][j];
        }
    }
    printf("Data ready\r\n");
	
	GraphPtr tempGraphPtr = initGraph(5, tempPtr);
	printf("num nodes = %d \r\n", tempGraphPtr -> numNodes);
	printf("Graph initialized\r\n");

	printf("Depth first visit:\r\n");
	initTranverse(tempGraphPtr);
	depthFirstTranverse(tempGraphPtr, 4);

	printf("\r\nWidth first visit:\r\n");
	initTranverse(tempGraphPtr);
	widthFirstTranverse(tempGraphPtr, 4);
}
int main(){
	testGraphTranverse();
	return 1;
}

运行结果:

Preparing data
Data ready
num nodes = 5
Graph initialized
Depth first visit:
4       1       0       3       2
Width first visit:
4       1       2       0       3

邻接表
1、图中一个顶点用一个一维数组存储
2、每个顶点的所有邻接点构成一个线性表,由于邻接点的个数不定,所以用单链表存储
请添加图片描述

定义邻接表结点:

typedef struct AdjacencyNode {
	int column;
	struct AdjacencyNode* next;
}AdjacencyNode, *AdjacentNodePtr;

定义邻接点结构:

typedef struct AdjacencyList {
	int numNodes;
	AdjacencyNode* headers;
}AdjacencyList, *AdjacencyListPtr;

创建邻接表:

AdjacencyListPtr graphToAdjacentList(GraphPtr paraPtr) {
	//Allocate space.
	int i, j, tempNum;
	AdjacentNodePtr p, q;
	tempNum = paraPtr->numNodes;
	AdjacencyListPtr resultPtr = (AdjacencyListPtr)malloc(sizeof(struct AdjacencyList));
	resultPtr->numNodes = tempNum;
	resultPtr->headers = (AdjacencyNode*)malloc(tempNum * sizeof(struct AdjacencyNode));
	
	//Fill the data.
	for (i = 0; i < tempNum; i ++) {
		//Initialize headers.
		p = &(resultPtr->headers[i]);
		p->column = -1;
		p->next = NULL;
 
		for (j = 0; j < tempNum; j ++) {
			if (paraPtr->connections[i][j] > 0) {
				//Create a new node.
				q = (AdjacentNodePtr)malloc(sizeof(struct AdjacencyNode));
				q->column = j;
				q->next = NULL;
 
				//Link.
				p->next = q;
				p = q;
			}
		}
	}
 
	return resultPtr;
}

广度优先遍历:

void widthFirstTranverse(AdjacencyListPtr paraListPtr , int paraStart) {
	printf("width first\n");
	int i, j, tempNode;
	AdjacentNodePtr p;
	i = 0;
	
	visitedPtr = (int*)malloc(paraListPtr->numNodes * sizeof(int));
	
	for (i = 0; i < paraListPtr->numNodes; i++) {
		visitedPtr[i] = 0;
	}
	 
	QueuePtr tempQueuePtr = initQueue();
	printf("%d\t", paraStart);
	visitedPtr[paraStart] = 1;
	enqueue(tempQueuePtr, paraStart);
	while (!isQueueEmpty(tempQueuePtr)) {
		tempNode = dequeue(tempQueuePtr);
		for (p =&(paraListPtr->headers[tempNode]) ; p != NULL; p = p->next) {
			j = p->column;
			
			if (visitedPtr[j]) continue;
			
			printf("%d ", j);
			visitedPtr[j] = 1;
			enqueue(tempQueuePtr, j);
		}
	}
	printf("\t\n");
} 

代码:

#include <stdio.h>
#include <malloc.h>
#define QUEUE_SIZE 10
int* visitedPtr;
//  图的结构体定义
typedef struct Graph{
	int** connections;
	int numNodes;
} *GraphPtr;
 
// 图的初始化
GraphPtr initGraph(int paraSize, int** paraData) {
	int i, j;
	GraphPtr resultPtr = (GraphPtr)malloc(sizeof(struct Graph));
	resultPtr -> numNodes = paraSize;
	resultPtr -> connections = (int**)malloc(paraSize * sizeof(int*));
	for (i = 0; i < paraSize; i ++) {
		resultPtr -> connections[i] = (int*)malloc(paraSize * sizeof(int));
		for (j = 0; j < paraSize; j ++) {
			resultPtr -> connections[i][j] = paraData[i][j];
		}
	}	
	return resultPtr;
}

typedef struct GraphNodeQueue{
	int* nodes;
	int front;
	int rear;
}GraphNodeQueue, *QueuePtr;
//队列初始化
QueuePtr initQueue(){
	QueuePtr resultQueuePtr = (QueuePtr)malloc(sizeof(struct GraphNodeQueue)); 
	resultQueuePtr->nodes = (int*)malloc(QUEUE_SIZE * sizeof(int));
	resultQueuePtr->front = 0;
	resultQueuePtr->rear = 1;
	return resultQueuePtr;
}
 
int isQueueEmpty(QueuePtr paraQueuePtr){
	if ((paraQueuePtr->front + 1) % QUEUE_SIZE == paraQueuePtr->rear) {
		return 1;
	}
 
	return 0;
}
 
void enqueue(QueuePtr paraQueuePtr, int paraNode){
	if ((paraQueuePtr->rear + 1) % QUEUE_SIZE == paraQueuePtr->front % QUEUE_SIZE) {
		printf("Error, trying to enqueue %d. queue full.\r\n", paraNode);
		return;
	}
	paraQueuePtr->nodes[paraQueuePtr->rear] = paraNode;
	paraQueuePtr->rear = (paraQueuePtr->rear + 1) % QUEUE_SIZE;
}

int dequeue(QueuePtr paraQueuePtr){
	if (isQueueEmpty(paraQueuePtr)) {
		printf("Error, empty queue\r\n");
		return 0;
	}
 
	paraQueuePtr->front = (paraQueuePtr->front + 1) % QUEUE_SIZE;
 
	return paraQueuePtr->nodes[paraQueuePtr->front];
}
 
 
// 定义邻接表结点结构
typedef struct AdjacencyNode {
	int column;
	struct AdjacencyNode* next;
}AdjacencyNode, *AdjacentNodePtr;
 
// 定义邻接表的结构体
typedef struct AdjacencyList {
	int numNodes;
	AdjacencyNode* headers;
}AdjacencyList, *AdjacencyListPtr;
 
//创建邻接表
AdjacencyListPtr graphToAdjacentList(GraphPtr paraPtr) {
	//Allocate space.
	int i, j, tempNum;
	AdjacentNodePtr p, q;
	tempNum = paraPtr->numNodes;
	AdjacencyListPtr resultPtr = (AdjacencyListPtr)malloc(sizeof(struct AdjacencyList));
	resultPtr->numNodes = tempNum;
	resultPtr->headers = (AdjacencyNode*)malloc(tempNum * sizeof(struct AdjacencyNode));
	
	//Fill the data.
	for (i = 0; i < tempNum; i ++) {
		//Initialize headers.
		p = &(resultPtr->headers[i]);
		p->column = -1;
		p->next = NULL;
 
		for (j = 0; j < tempNum; j ++) {
			if (paraPtr->connections[i][j] > 0) {
				//Create a new node.
				q = (AdjacentNodePtr)malloc(sizeof(struct AdjacencyNode));
				q->column = j;
				q->next = NULL;
 
				//Link.
				p->next = q;
				p = q;
			}
		}
	}
 
	return resultPtr;
}
 
void printAdjacentList(AdjacencyListPtr paraPtr) {
	int i;
	AdjacentNodePtr p;
	int tempNum = paraPtr->numNodes;
 
	printf("This is the graph:\r\n");
	for (i = 0; i < tempNum; i ++) {
		p = paraPtr->headers[i].next;
		while (p != NULL) {
			printf("%d, ", p->column);
			p = p->next;
		}
		printf("\r\n");
	}
}
// 广度优先遍历 
void widthFirstTranverse(AdjacencyListPtr paraListPtr , int paraStart) {
	printf("width first\n");
	int i, j, tempNode;
	AdjacentNodePtr p;
	i = 0;
	
	visitedPtr = (int*)malloc(paraListPtr->numNodes * sizeof(int));
	
	for (i = 0; i < paraListPtr->numNodes; i++) {
		visitedPtr[i] = 0;
	}
	 
	QueuePtr tempQueuePtr = initQueue();
	printf("%d\t", paraStart);
	visitedPtr[paraStart] = 1;
	enqueue(tempQueuePtr, paraStart);
	while (!isQueueEmpty(tempQueuePtr)) {
		tempNode = dequeue(tempQueuePtr);
		for (p =&(paraListPtr->headers[tempNode]) ; p != NULL; p = p->next) {
			j = p->column;
			
			if (visitedPtr[j]) continue;
			
			printf("%d ", j);
			visitedPtr[j] = 1;
			enqueue(tempQueuePtr, j);
		}
	}
	printf("\t\n");
} 
 
void testGraphTranverse() {
	int i, j;
	int myGraph[5][5] = { 
		{0, 1, 0, 1, 0},
		{1, 0, 1, 0, 1}, 
		{0, 1, 0, 1, 1}, 
		{1, 0, 1, 0, 0}, 
		{0, 1, 1, 0, 0}};
	int** tempPtr;
	printf("Preparing data\r\n");
		
	tempPtr = (int**)malloc(5 * sizeof(int*));
	for (i = 0; i < 5; i ++) {
		tempPtr[i] = (int*)malloc(5 * sizeof(int));
	}
	 
	for (i = 0; i < 5; i ++) {
		for (j = 0; j < 5; j ++) {
			tempPtr[i][j] = myGraph[i][j];
		}
	}
 
	printf("Data ready\r\n");
	
	GraphPtr tempGraphPtr = initGraph(5, tempPtr);
	AdjacencyListPtr tempListPtr = graphToAdjacentList(tempGraphPtr);
 
	printAdjacentList(tempListPtr);
 
	widthFirstTranverse(tempListPtr, 4);
}
 
int main(){
	testGraphTranverse();
	return 1;
}

运行结果:

Preparing data
Data ready
This is the graph:
1, 3,
0, 2, 4,
1, 3, 4,
0, 2,
1, 2,
width first
4       1 2 0 3

图在存储时更多的使用链式存储,具体的存储方法有邻接表、邻接多重表、十字链表。在图中边比较稀疏的时候,使用邻接表比邻接矩阵更加节省空间

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值