---
title: "图的广度深度遍历（邻接矩阵）"
author: "vearne"
date: "2012-07-11T23:25:41Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-07-11T23:25:41Z"
id: 1585605
url: "https://vearne.iteye.com/blog/1585605"
---

```
#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);
}
```