数据结构—邻接表的BFS
原理:参考趣学数据结构
代码:
队列代码:
# pragma once
# define elemType int
# define N 100
# include <stdlib.h>
typedef struct dQueue { int data; struct dQueue * next;
} dQueue;
typedef struct queue { dQueue * front, * rear;
} queue;
bool initQueue ( queue & Queue) { Queue. front = Queue. rear = ( dQueue* ) malloc ( sizeof ( dQueue) ) ; if ( ! Queue. front) { return false; } Queue. front-> next = NULL ; return true;
}
int getQueueTopElem ( queue & Queue) { int u = - 1 ; if ( Queue. front != Queue. rear) { dQueue* p = Queue. front-> next; u = p-> data; } return u;
}
bool enQueue ( queue & Queue, int e) { dQueue* p = Queue. rear; dQueue* s = ( dQueue* ) malloc ( sizeof ( dQueue) ) ; s-> data = e; s-> next = NULL ; p-> next = s; Queue. rear = s; return true;
}
bool deQueue ( queue & Queue, int & e) { if ( Queue. front == Queue. rear) { return false; } dQueue* p = Queue. front-> next; e = p-> data; Queue. front-> next = p-> next; if ( p == Queue. rear) { Queue. rear = Queue. front; } delete p; return true;
}
bool emptyQueue ( queue Queue) { if ( Queue. front == Queue. rear) { return true; } return false;
}
BFS代码:
# include <stdio.h>
# include <stdlib.h>
# include "queue.h"
# define typeNode int
# define N 100
int degree[ N] ;
int result[ N] ;
bool visited[ N] ;
typedef struct dNode { int data; struct dNode * next;
} dNode;
typedef struct mNode { typeNode data; dNode * first;
} mNode;
typedef struct { mNode vNode[ N] ; int vNum, eNum;
} zNode;
void init ( zNode & ZNode) { printf ( "规定顶点从0开始取\n" ) ; scanf_s ( "%d%d" , & ZNode. vNum, & ZNode. eNum) ; for ( int i = 0 ; i < ZNode. vNum; i++ ) { scanf_s ( "%d" , & ZNode. vNode[ i] . data) ; ZNode. vNode[ i] . first = NULL ; } for ( int i = 0 ; i < ZNode. eNum; i++ ) { int u, v; scanf_s ( "%d%d" , & u, & v) ; dNode* p = new dNode ( ) ; p-> data = v; p-> next = ZNode. vNode[ u] . first; ZNode. vNode[ u] . first= p; }
}
void print14 ( zNode ZNode) { printf ( "遍历链表:\n" ) ; for ( int i = 0 ; i < ZNode. vNum; i++ ) { dNode* temp = ZNode. vNode[ i] . first; printf ( "%d ->" , ZNode. vNode[ i] . data) ; while ( temp) { printf ( "%d ->" , temp-> data) ; temp = temp-> next; } printf ( "NULL\n" ) ; }
}
void BFSLinkGraph ( zNode ZNode, int u) { queue Queue; initQueue ( Queue) ; visited[ u] = true; enQueue ( Queue, u) ; while ( ! emptyQueue ( Queue) ) { u = getQueueTopElem ( Queue) ; printf ( "%d " , u) ; int e = - 1 ; deQueue ( Queue, e) ; dNode* p= ZNode. vNode[ u] . first; while ( p) { int i = p-> data; if ( ! visited[ i] ) { visited[ i] = true; enQueue ( Queue, i) ; } p = p-> next; } }
}
int main ( ) { zNode ZNode; printf ( "邻接表的构造:\n" ) ; init ( ZNode) ; print14 ( ZNode) ; for ( int i = 0 ; i < ZNode. vNum; i++ ) { visited[ i] = false; } printf ( "BFS遍历邻接表\n" ) ; BFSLinkGraph ( ZNode, 0 ) ; printf ( "\n" ) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度为O(n+e),空间复杂度为O(n)
如果存在什么问题,欢迎批评指正!谢谢!