zoukankan      html  css  js  c++  java
  • Graph-BFS-Fly-图的广度优先遍历-最小转机问题

    #include <iostream>
    #include <queue>
    
    using namespace std;
    
    /*
    5 7 1 5
    1 2
    1 3
    2 3
    2 4
    3 4
    3 5
    4 5
    
    2
    --------------------------------
    Process exited with return value 0
    Press any key to continue . . .
    */ 
    
    class Node
    {
    public:
    	Node(int _x, int _z);
    	
    public:
    	int x;
    	int z;
    };
    
    Node::Node(int _x, int _z)
    {
    	this->x = _x;
    	this->z = _z; 
    }
    
    const int infinity = 999999;
    int vertx, edge, start, end;
    int Graph[20][20] = {0}, book[20] = {0};
    queue<Node> qgraph;
    
    void BFS()
    {
    	book[start] = 1;
    	Node firstnode(start, 0);
    	qgraph.push(firstnode);
    	
    	while(!qgraph.empty())
    	{
    		int flag = 0;
    		
    		int x = qgraph.front().x;
    		
    		for(int i = 1; i <= vertx; i++)
    		{
    			if(Graph[x][i] != infinity && book[i] == 0)
    			{
    				book[i] = 1;
    				
    				Node node(i, qgraph.front().z + 1); 
    				
    				qgraph.push(node);
    			}
    			
    			if(qgraph.back().x == end)
    			{
    				flag = 1;
    				break;	
    			}
    		}
    		
    		if(flag == 1)
    		{
    			break;
    		}
    		
    		qgraph.pop();
    	}
    	
    	return;
    }
    
    int main()
    {
    	cin >> vertx >> edge >> start >> end;
    	for(int i = 1; i <= vertx; i++)
    	{
    		for(int j = 1; j <= vertx; j++)
    		{
    			if(i == j)
    			{
    				Graph[i][j] = 0;
    			}
    			Graph[i][j] = infinity;
    		}
    	} 
    	
    	for(int j = 1; j <= edge; j++)
    	{
    		int x, y;
    		cin >> x >> y;
    		Graph[x][y] = 1;
    		Graph[y][x] = 1;
    	}
    	
    	BFS();
    	
    	cout << endl << qgraph.back().z;
    		
    	return 0; 
    } 
    

      

  • 相关阅读:
    Linux常用命令_(系统设置)
    Linux常用命令_(系统管理)
    Linux常用命令_(基本命令)
    敏捷测试的流程
    Web测试Selenium:如何选取元素
    Selenium学习
    Selenium介绍
    Selenium测试规划
    HTTPS传输协议原理
    常见的加密算法
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/6388851.html
Copyright © 2011-2022 走看看