#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <queue> using namespace std; #define VERTEX_NUM 8 bool visited[VERTEX_NUM + 1]; // 访问标志数组(备忘表) int FirstAdjVex(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1], int v) { for (int j = 1; j <= VERTEX_NUM; j++) { if (G[v][j] == 1) return j; } cout << "该点是孤立点" << endl; // 连通图则不会到这一步 return -1; } int NextAdjVex(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1], int v, int w) { for (int j = w + 1; j <= VERTEX_NUM; j++) { if (G[v][j] == 1) return j; } return -1; } void BFSTraverse(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1]) { // 按广度优先非递归遍历图G。使用辅助队列Q和访问标志数组visited。 int v; int w; queue<int> Q; int u; for (v = 1; v <= VERTEX_NUM; ++v) visited[v] = false; for (v = 1; v <= VERTEX_NUM; ++v) { if (!visited[v]) { // v尚未访问 visited[v] = true; cout << v << endl; Q.push(v); while (!Q.empty()) { u = Q.front(); Q.pop(); // 队头元素出队并置为u for (w = FirstAdjVex(G, u); w >= 0; w = NextAdjVex(G, u, w)) { if (!visited[w]) { // u的尚未访问的邻接顶点w入队列Q visited[w] = true; cout << w << endl; Q.push(w); } } } } } } void CreatAdjMatrixGraph(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1]) { int a; int b; while (cin >> a >> b, !(a == 0 && b == 0)) { //以0 0作为输入结束 G[a][b] = 1; G[b][a] = 1; } } void Display(bool G[VERTEX_NUM + 1][VERTEX_NUM + 1]) { for (int i = 1; i <= VERTEX_NUM; i++) { // 输出邻接矩阵 for (int j = 1; j <= VERTEX_NUM; j++) { cout << G[i][j] << ' '; } cout << endl; } } int main(int argc, char **argv) { freopen("cin.txt", "r", stdin); bool G[VERTEX_NUM + 1][VERTEX_NUM + 1] = {0}; CreatAdjMatrixGraph(G); Display(G); BFSTraverse(G); return 0; } /* cin.txt: 1 2 2 4 2 5 8 4 8 5 1 3 3 6 3 7 6 7 0 0 */
运行结果: