代码来源于《啊哈!算法》。
1、深度优先遍历:
(1)无权值
#include<stdio.h>
int book[101],n, e[1001][1001], sum;
void DFS(int cur)
{int h;sum++;printf("%d ", cur);//目前所在点进行的操作,可以更复杂if (sum == n)return;for (h = 1; h <= n; h++)if (book[h] == 0 && e[cur][h] == 1){book[h] = 1;DFS(h);}return;
}
int main(void)
{int m;int a, b;printf("顶点数:");scanf_s("%d", &n);printf("边数:");scanf_s("%d", &m);for(int i=1;i<=n;i++)for (int j = 1; j < n; j++){if (i == j)e[i][j] = 0;elsee[i][j] = 99999999;}for (int k = 1; k <= m; k++){scanf_s("%d%d", &a, &b);e[a][b] = 1;e[b][a] = 1;}book[1] = 1;DFS(1);getchar(); getchar();return 0;
}
(2)有权值
void DFS(int cur, int dis)
{if (dis > min)//dis是目前所走的距离,min是已经查出的路线中最小的路径和return;if (cur = destination)//destination是目的地的编号{if (dis < min)min = dis;return;}for (int i = 1; i <= n; i++)if (book[i] == 0 && e[cur][i] != inf){book[i] = 1;DFS(i, dis + e[cur][i]);book[i] = 0;}return;
}
2、广度优先遍历
#include<stdio.h>
int main(void)
{int n, m;int a, b;int i, j;int cur;int book[101] = { 0 };int e[101][101];int que[10001], head, tail;printf("顶点数:");scanf_s("%d", &n);printf("边数:");scanf_s("%d", &m);for(int i=1;i<=n;i++)for (int j = 1; j < n; j++){if (i == j)e[i][j] = 0;elsee[i][j] = 99999999;}for (int k = 1; k <= m; k++){scanf_s("%d%d", &a, &b);e[a][b] = 1;e[b][a] = 1;}head = 1;tail = 1;que[tail] = 1;tail++;book[1] = 1;while (head < tail){cur = que[head];for(i=1;i<=n;i++)if (book[i] == 0&&e[cur][i] == 1){que[tail] = i;tail++;book[i] = 1;}if (tail > n)break;head++;//并没有真正意义上的出队。}for (i = 1; i <tail; i++)printf("%d ", que[i]);getchar(); getchar();return 0;
}