zoukankan      html  css  js  c++  java
  • Graph-BFS-图的广度优先遍历

    #include <iostream>
    #include <queue>
    
    using namespace std;
    
    /*
    5 5
    1 2
    1 3
    1 5
    2 4
    3 5
    1 2 3 5 4
    --------------------------------
    Process exited with return value 0
    Press any key to continue . . .
    */
    
    int sum = 1;
    int vertx, edge;
    int Graph[20][20] = {0}, book[20] = {0};
    
    void BFS()
    {	
    	//队列 
    	queue<int> qgraph;
    
    	//标记第一个元素已经访问,并压入队列中。 
    	book[1] = 1;
    	qgraph.push(1);
    	
    	//当队列不为空时 
    	while(!qgraph.empty())
    	{
    		int x = qgraph.front();
    		for(int i = 1; i <= vertx; i++)
    		{
    			if(Graph[x][i] == 1 && book[i] == 0)
    			{
    				sum++; 
    				book[i] = 1;
    				qgraph.push(i);
    			}
    		}
    		
    		cout << qgraph.front() << " ";
    		qgraph.pop();
    	}
    	
    	return;
    }
    
    int main()
    {
    	cin >> vertx >> edge;
    	
    	for(int i = 1; i <= vertx; i++)
    	{
    		for(int j = 1; j <= vertx; j++)
    		{
    			if(i == j) Graph[i][j] = 0;
    			Graph[i][j] = 999999;
    		}
    	}
    	
    	for(int i = 1; i <= edge; i++)
    	{
    		int x, y;
    		cin >> x >> y;
    		Graph[x][y] = 1;
    		Graph[y][x] = 1;
    	}
    	
    	BFS();
    	
    	return 0;
    } 
    

      

  • 相关阅读:
    反射详解六
    反射详解五
    反射详解四
    反射详解三
    反射详解二
    mysql行转列
    mysql增删改查
    视图的使用
    js过滤
    错误集
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/6388844.html
Copyright © 2011-2022 走看看