数据结构—邻接矩阵的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 N 100
# define elemType int
# define INF ( ( ( unsigned int ) ( - 1 ) ) >> 1 )
bool visited[ N] ;
typedef struct GraphMatrix { elemType vNode[ N] [ N] ; int vNum, eNum;
} GraphMatrix;
void initGMaxtix ( GraphMatrix & G) { printf ( "输入顶点数和边数\n" ) ; scanf_s ( "%d%d" , & G. vNum, & G. eNum) ; for ( int i = 0 ; i < G. vNum; i++ ) { for ( int j = 0 ; j < G. vNum; j++ ) { G. vNode[ i] [ j] = INF; } } printf ( "输入顶点v1到顶点v2和其边的权重\n" ) ; for ( int i = 0 ; i < G. eNum; i++ ) { int v1, v2, weights; scanf_s ( "%d%d%d" , & v1, & v2, & weights) ; G. vNode[ v1] [ v2] = weights; }
}
void print13 ( GraphMatrix G) { printf ( "邻接矩阵如下:\n" ) ; for ( int i = 0 ; i < G. vNum; i++ ) { for ( int j = 0 ; j < G. vNum; j++ ) { printf ( "%d " , G. vNode[ i] [ j] ) ; } printf ( "\n" ) ; }
}
void BFSMatrixGraph ( GraphMatrix G, 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) ; for ( int i = 0 ; i < G. vNum; i++ ) { if ( ! visited[ i] && G. vNode[ u] [ i] < INF) { visited[ i] = true; enQueue ( Queue, i) ; } } }
}
int main ( ) { GraphMatrix G; initGMaxtix ( G) ; print13 ( G) ; printf ( "\n" ) ; for ( int i = 0 ; i < G. vNum; i++ ) { visited[ i] = false; } printf ( "BFS遍历邻接矩阵\n" ) ; BFSMatrixGraph ( G, 0 ) ; printf ( "\n" ) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(n x n),空间复杂度为O(n)
如果存在什么问题,欢迎批评指正!谢谢!