在之前的博文中,介绍了图的深度优先遍历,并分别进行了递归和非递归实现。BFS 无法递归实现,最广泛的实现是利用队列(queue)。这与DFS的栈实现是极其相似的,甚至代码几乎都很少需要改动。从给定的起点节点开始,依次将其邻接节点全部塞入队列,每次访问一个节点时将其pop()出队列,并将其邻接节点也塞入队列。直到队列为空,算法结束。
代码实现并无太大障碍,c++实现:
1 #include <iostream> 2 #include <queue> 3 using namespace std; 4 5 #define MAX 20 6 #define START 1 7 8 int visited[MAX]; 9 int map[MAX][MAX]; 10 11 void bfs(int start, int n){ 12 queue<int> q; 13 int q_top; 14 cout<<start<<" "; 15 visited[start] = 1; 16 for (int i = 1; i <= n ;i++ ) { 17 if(map[start][i] == 1 && visited[i] == 0){ 18 q.push(i); 19 visited[i] = 1; 20 } 21 } 22 while(!q.empty()){ 23 q_top = q.front(); 24 q.pop(); 25 cout<<q_top<<" "; 26 for(int i = 1; i <= n; i++ ){ 27 if(map[q_top][i] == 1 && visited[i] == 0){ 28 q.push(i); 29 visited[i] = 1; 30 } 31 } 32 } 33 34 } 35 36 int main(int argc, const char * argv[]) { 37 int num_vex,num_edge,x,y; 38 cout<<"Input number of nodes and edges >> "; 39 cin>>num_vex>>num_edge; 40 for(int i=0;i<MAX;i++){ 41 for(int j = 0;j < MAX;j++){ 42 map[i][j] = 0; 43 } 44 } 45 for(int i = 1;i <= num_vex;i++){ 46 visited[i] = 0; 47 } 48 cout<<"Input edges, "<<num_edge<<" left >> "; 49 for(int i = 1;i <= num_edge;i++){ 50 cin>>x>>y; 51 map[x][y] = map[y][x] = 1; 52 cout<<"Input edges, "<<(num_edge-i)<<" left >> "; 53 } 54 bfs(START, num_vex); 55 return 0; 56 }
时间: 2024-10-12 21:13:08