zoukankan      html  css  js  c++  java
  • 图——广度优先遍历(邻接矩阵存储)

    // Graph,BFS
    #include <cstdio>
    #include <iostream>
    #include <queue>
    using namespace std;
    
    int graph[100][100]={0};
    int visited[100]={0};
    queue <int> q;
    void Initgraph()
    {
    	int n,i;
    	int p,q;
    	cout<<"Input the edge num:"<<endl;
    	cin>>n;
    	cout<<"Input the connected p and q:"<<endl;
    	for(i=0;i<n;i++)
    	{
    		cin>>p>>q;
    		graph[p][q]=graph[q][p]=1;
    	}
    }
    void visit(int v)
    {
    	cout<<v<<" ";
    }
    int  getneighbor(int v)
    {
    	int i;
    	for(i=0;i<100;i++)
    	{	
    		if(graph[v][i]==1)
    			if(!visited[i])
    			{
    					return i;	
    			}
    	}
    	return -1;
    }
    void BFS(int v)
    {
    	cout<<"BFS sequence:"<<endl;
    	visit(v);
    	visited[v]=1;
    	q.push(v);
    	while(!q.empty())
    	{
    		int u=q.front();
    		q.pop();
    		int w=getneighbor(u);
    		while(w!=-1)
    		{
    			visit(w);
    			visited[w]=1;
    			q.push(w);
    			w=getneighbor(u);			
    		}
    
    	} 
    	
    	
    	
    }
    int main()
    {
    	Initgraph();
    	cout<<"Please input the start vex:"<<endl;
    	int v;
    
    	cin>>v;
    	BFS(v);
    	return 0;
    }

  • 相关阅读:
    设计模式之《工厂方法》
    设计模式之 《简单工厂》
    fegin 调用源码分析
    ajax上传预览
    ajax小应用
    ajax执行流程1
    ajax异步post方法
    ajax get异步方法
    js ajax请求流程
    form表单提交
  • 原文地址:https://www.cnblogs.com/qiangz/p/8447215.html
Copyright © 2011-2022 走看看