广度优先搜索
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <queue>
using namespace std;
const int N = 10005;
bool vis[N];
int cnt,n,m;
queue<int> Q;
int head[N],to[N],next[N],w[N];
int T[N],ct;
void Init()
{
ct = 0;
cnt = 0;
memset(head,-1,sizeof(head));
}
void add(int u,int v,int c)
{
to[cnt] = v; w[cnt] = c; next[cnt] = head[u]; head[u] = cnt++;
to[cnt] = u; w[cnt] = c; next[cnt] = head[v]; head[v] = cnt++;
}
void BFS(int s)
{
memset(vis,false,sizeof(vis));
while(!Q.empty()) Q.pop();
vis[s] = true;
T[ct++] = s;
Q.push(s);
while(!Q.empty())
{
int u = Q.front();
Q.pop();
for(int i=head[u]; ~i; i=next[i])
{
int v = to[i];
if(!vis[v])
{
vis[v] = true;
T[ct++] = v;
Q.push(v);
}
}
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
Init();
for(int i=1;i<=n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v,1);
}
BFS(1);
for(int i=0;i<ct;i++)
cout<<T[i]<<" ";
puts("");
}
return 0;
}
深度优先遍历
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <queue>
using namespace std;
const int N = 10005;
bool vis[N];
int cnt,n,m;
int head[N],to[N],next[N],w[N];
int T[N],ct;
void Init()
{
ct = 0;
cnt = 0;
memset(head,-1,sizeof(head));
memset(vis,false,sizeof(vis));
}
void add(int u,int v,int c)
{
to[cnt] = v; w[cnt] = c; next[cnt] = head[u]; head[u] = cnt++;
to[cnt] = u; w[cnt] = c; next[cnt] = head[v]; head[v] = cnt++;
}
void DFS(int s)
{
vis[s] = true;
T[ct++] = s;
for(int i=head[s]; ~i; i=next[i])
{
int v = to[i];
if(!vis[v])
{
printf("%d, %d\n",s,v);
DFS(v);
}
}
}
int main()
{
int n;
while(~scanf("%d",&n))
{
Init();
for(int i=1;i<=n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add(u,v,1);
}
DFS(1);
for(int i=0;i<ct;i++)
cout<<T[i]<<" ";
puts("");
}
return 0;
}