输出使用深度优先算法访问树的顺序;
yuanzhen:~/C_script$ cat dfs_two.cpp
#include <vector> #include <iostream> #include <cstdlib>using std::cout;
using std::endl; using std::vector;vector<vector<int> > vec;
vector<int> book(13,0); vector<int> result(13,0);void show(vector<vector<int> > avec)
{ vector<vector<int> >::const_iterator cit; vector<int>::const_iterator it;for(cit=avec.begin(); cit!=avec.end();++cit)
{ vector<int> ivec=(*cit); for(it=ivec.begin();it!=ivec.end();++it) { cout << *it << " "; } cout << endl; } } vector<vector<int> > init() { int arr[11][2]={ {1,2},{1,7},{1,8},{2,3},{2,6},{3,4},{3,5},{8,9},{8,12},{9,10},{9,11}};vector<vector<int> >avec(13, vector<int>(13,0));
for(int i=1;i<13;++i) avec[i][0]=i;for(int j=1;j<13;++j)
avec[0][j]=j;for(int k=0;k<11;++k)
{ int x=arr[k][0]; int y=arr[k][1];avec[x][y]=1;
avec[y][x]=1; } return avec; }void dfs(int node, int step)
{ cout << node << endl; for(int i=1;i<13;++i) { if(vec[node][i]==1 && book[i]==0) { book[i]=1; dfs(i, step+1); book[i]=0; } } }int main(int argc, char** argv)
{ vec=init(); show(vec); book[1]=1; dfs(1,1); } ##################################结果
0 1 2 3 4 5 6 7 8 9 10 11 12
1 0 1 0 0 0 0 1 1 0 0 0 0 2 1 0 1 0 0 1 0 0 0 0 0 0 3 0 1 0 1 1 0 0 0 0 0 0 0 4 0 0 1 0 0 0 0 0 0 0 0 0 5 0 0 1 0 0 0 0 0 0 0 0 0 6 0 1 0 0 0 0 0 0 0 0 0 0 7 1 0 0 0 0 0 0 0 0 0 0 0 8 1 0 0 0 0 0 0 0 1 0 0 1 9 0 0 0 0 0 0 0 1 0 1 1 0 10 0 0 0 0 0 0 0 0 1 0 0 0 11 0 0 0 0 0 0 0 0 1 0 0 0 12 0 0 0 0 0 0 0 1 0 0 0 0 ------------------------------ 1 2 3 4 5 6 7 8 9 10 11 12