图的遍历
关于图的遍历算法,一般而言包括广度优先遍历和深度优先遍历两种。其中,广度优先遍历利用队列实现,深度优先遍历利用函数的递归栈实现。为了入门的方便,在这里我们使用邻接矩阵来存储图的信息。
对于一个节点数为n(1 ≤ n ≤ 100)且无独立节点的的图,图中有m(1 ≤ n ≤ 1000)条无向边连接x点与y点,给出遍历起始点s。下面给出对其进行广度优先遍历的实现代码:
#include <iostream> #include <cstdio> using namespace std; const int MAXN = 101; const int MAXM = 10001; const int MAXL = 200001; int que[MAXL]; bool book[MAXN]; int map[MAXN][MAXN]; int n, m, s, x, y, head, tail, now; int main() { scanf("%d%d%d", &n, &m, &s); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { book[i] = false; if(i == j) { map[i][j] = 1; } else { map[i][j] = -1; } } } for(int i = 1; i <= m; i++) { scanf("%d%d", &x, &y); map[x][y] = 1; map[y][x] = 1; } head = 0; tail = 1; que[1] = s; book[s] = true; while(head < tail) { head++; now = que[head]; for(int i = 1; i <= n; i++) { if(!book[i] && map[now][i] == 1) { tail++; que[tail] = i; book[i] = true; } } printf("%d ", que[head]); } return 0; }
接下来是深度优先遍历的代码实现:
#include <iostream> #include <cstdio> using namespace std; const int MAXN = 101; int map[MAXN][MAXN]; bool book[MAXN]; int n, m, s, x, y; void dfs(int now) { for(int i = 1; i <= n; i++) { if(!book[i]) { if(map[now][i] == 1) { printf("%d ", i); book[i] = true; dfs(i); } } } } int main() { scanf("%d%d%d", &n, &m, &s); for(int i = 1; i <= n; i++) { book[i] = false; for(int j = 1; j <= n; j++) { if(i == j) { map[i][j] = 1; } else { map[i][j] = -1; } } } for(int i = 1; i <= m; i++) { scanf("%d%d", &x, &y); map[x][y] = 1; map[y][x] = 1; } dfs(s); return 0; }
圆满完成。