`
vearne
  • 浏览: 18284 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

图的广度深度遍历(邻接矩阵)

阅读更多

#include <iostream>
#include <queue>
#include <algorithm>
#include <stack>
using namespace std;
int a[5][5]={{0,1,0,1,0},{1,0,1,0,1},{0,1,0,1,1},{1,0,1,0,0},{1,0,1,0,0}};
template<int n>
void bfs(int i){
	queue<int> q;
	bool flag[n];
	memset(flag,false,n);
	q.push(i);
	flag[i]=true;
	while(!q.empty()){
		int k = q.front();
		q.pop();
		cout<<k<<" ";
		for(int j=0;j<n;j++){
			if(a[k][j]&&!flag[j]){
				q.push(j);
				flag[j]=true;
			}
		}
	}


}
template<int n>
void dfs(int i){
	stack<int> s;
	bool flag[n];
	memset(flag,false,n);
	s.push(i);
	flag[i]=true;
	while(!s.empty()){
		int k= s.top();
		s.pop();
		cout<<k<<" ";
		for(int j=0;j<n;j++){
			if(a[k][j]&&!flag[j]){
				s.push(j);
				flag[j]=true;
			}
		}
	}
}
int main(){
	bfs<5>(0);
	cout<<endl;
	dfs<5>(0);
}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics