戈尼斯堡七桥问题——C++实现

将实际问题先抽象成模型,再利用矩阵存储数据

/*
算法:oddVertexNum
输入:二维数组mat[][],顶点个数n
输出:通奇数桥的顶点个数count
    1.count初始化为0;
    2.下标i从0~n-1重复执行以下操作;
        2.1计算第i行元素之和degree;
        2.2如果degree为奇数,则count++
    3.返回count
*/
//将oddVertexNum定义为类EulerCircuit的成员函数,EulerCircuit的成员变量表示七桥问题中对应的数据模型。
//主函数首先定义对象变量G,然后调用函数oddVertexNum计算图模型中通奇数桥的顶点个数,最后根据欧拉规则判断是否存在欧拉回路。
#include <iostream>
using namespace std;

const int MaxSize=4;#常量声明
class EulerCircuit {
public:
    EulerCircuit(int **a, int n);   //构造函数
    ~EulerCircuit();  //析构函数
    int oddVertexNum();  //求图中度为奇数的顶点个数
private:
    int mat[MaxSize][MaxSize];  //二维数组存储图
    int vertexNum;  //顶点个数
};

EulerCircuit :: EulerCircuit(int a[][MaxSize], int n)
{
for(int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
mat[i][j] = a[i][j];
vertexNum = n;
}
int EulerCircuit :: oddVertexNum( )
{
int count = 0, i, j, degree;
for (i = 0; i < vertexNum; i++) // 依次累加每一行元素
{
degree = 0; // 记录通过顶点i的边数
for (j = 0; j < vertexNum; j++)
degree = degree + mat[i][j];
if (degree % 2 != 0)
count++;
}
return count;
}

int main( )
{
int a[4][4] = {{0, 1, 2, 2},{1, 0, 1, 1},{2, 1, 0, 0},{2, 1, 0, 0}};
EulerCircuit G{a, 4};
int num = G.oddVertexNum( ); //调用函数得到通奇数桥的顶点个数
if (num >= 2) //两个以上的顶点通奇数桥
cout << num << "个地方通奇数桥,不存在欧拉回路" << endl;
else //没有顶点通奇数桥
cout << "存在欧拉回路" << endl;
return 0;
}
posted @ 2022-08-23 17:40  CUHKSZ丶Travis  阅读(276)  评论(0)    收藏  举报