DFS的模板
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <memory.h>
#include <limits.h>
using namespace std;
int k, m, e[105][105], book[105];
void dfs(int cur)//深度搜索,递归实现
{
int i;
for (i = 0; i < k; i++)
{
if (book[i] == 0 && e[cur][i] == 1)
{
book[i] = 1;
printf(" %d", i);
dfs(i);
}
}
return;
}
int main()
{
int n;
scanf("%d", &n);
while (n--)
{
scanf("%d %d", &k, &m);
int i, j;
for (i = 0; i < k; i++)
{
book[i] =0;
for (j = 0; j < k; j++)
{
if (i == j)
e[i][j] = 0;
else
e[i][j] = INT_MAX;
}
}
for (i = 0; i < m; i++)
{
int a, b;
scanf("%d %d", &a, &b);
e[a][b] = e[b][a] = 1;
}
book[0] = 1;
printf("0");
dfs(0);
printf("\n");
}
return 0;
}
来个BFS的模板
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <stdlib.h>
#include <memory.h>
#include <limits.h>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
while (n--)
{
int k, m, t;
scanf("%d %d %d", &k, &m, &t);
int e[105][105], book[105], que[105];
memset(book, 0, sizeof(book));
int i, j;
for (i = 0; i < k; i++)
for (j = 0; j < k; j++)
if (i == j)
e[i][j] = 0;
else
e[i][j] = INT_MAX;
for (i = 0; i < m; i++)
{
int a, b;
scanf("%d %d", &a, &b);
e[a][b] = e[b][a] = 1;
}
int head = 0, tail = 0;
book[t] = 1;
que[tail] = t;
tail++;
while (head < tail)
{
int cur = que[head++];
for (i = 0; i < k; i++)
{
if (book[i] == 0 && e[cur][i] == 1)
{
que[tail++] = i;
book[i] = 1;
}
}
}
for (i = 0; i < tail; i++)
printf("%d%c", que[i], i == tail - 1 ? '\n' : ' ');
}
return 0;
}