• 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; 
    } 
    

      

  • 相关阅读:
    字符串面试题:将句子的单词序倒置
    字符串面试题:将整型转换为字符串
    QML定时器
    QML按键事件处理
    QML鼠标事件实现变色矩形
    QML动态加载组件
    QML鼠标区域控制
    属性绑定与赋值
    设置虚拟机的本地端口映射
    关于修改banner信息;nginx反向代理apache应用
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/6388851.html
Copyright © 2020-2023  润新知