zoukankan      html  css  js  c++  java
  • 图的遍历——BFS(队列实现)

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <queue>
    #include <malloc.h>
    
    using namespace std;
    
    const int VERTEX_NUM = 20;
    const int INFINITY = 0x7fffffff; 		// 最大int型数,表示权的无限值 
    
    bool vis[VERTEX_NUM];
    
    class Graph {
    public:
    	int vexNum;
    	int edgeNum;
    	int vex[VERTEX_NUM];
    	int arc[VERTEX_NUM][VERTEX_NUM]; 
    };
    
    void createGraph(Graph &G)
    {
    	cout << "please input vexNum and edgeNum: ";
    	cin >> G.vexNum >> G.edgeNum;
    	for (int i = 0; i != G.vexNum; ++i) {
    		cout << "please input no" << i+1 << " vertex: ";
    		cin >>  G.vex[i];
    	}
    	for (int i = 0; i != G.vexNum; ++i) {
    		for (int j = 0; j != G.vexNum; ++j) {
    			G.arc[i][j] = INFINITY;
    		}
    	}
    	for (int k = 0; k != G.edgeNum; ++k) {
    		cout << "please input the vertex of edge(vi, vj) and weight: ";
    		int i, j, w;
    		cin >> i >> j >> w;
    		G.arc[i][j] = w;
    		G.arc[j][i] = G.arc[i][j];			// 无向图 
    	}
    }
    
    void BFSTraverse(const Graph &G)
    {
    	memset(vis, false, VERTEX_NUM);
    	queue<int> q;
    	for (int i = 0; i != G.vexNum; ++i) {
    		if (!vis[i]) {
    			vis[i] = true;
    			cout << G.vex[i] << " ";
    			q.push(i);
    			while (!q.empty()) {
    				int m = q.front();	// 队列的作用正在于此 
    				q.pop();		// ...
    				for (int j = 0; j != G.vexNum; ++j) {
    					if (G.arc[m][j] != INFINITY && !vis[j]) {
    						cout << G.vex[j] << " ";
    						q.push(j);
    						vis[j] = true;
    					}
    				}
    			}
    		}
    	}
    } 
    
    int main()
    {
    	Graph G;
    	createGraph(G);
    	BFSTraverse(G);
    	return 0;
    } 
    

      

  • 相关阅读:
    为什么要使用虚拟内存?
    iptables系列
    MySQL 加锁处理分析
    血战的浏览器历史
    TCP协议详解
    OAuth 2.0详解
    Redis 和 I/O 多路复用
    Kubernetes的十大使用技巧
    Nginx动态路由的新姿势:使用Go取代lua
    个人博客实现Archives查询小记
  • 原文地址:https://www.cnblogs.com/xzxl/p/8646694.html
Copyright © 2011-2022 走看看