有向图的邻接矩阵

来源:互联网 发布:淘宝众筹成功怎么赚钱 编辑:程序博客网 时间:2024/05/01 13:08

所谓用邻接矩阵,是用一个二维数组存储,边使用矩阵来构建模型,这使得每一个顶点和其它顶点之间都有边的有无 的 表示的机会。若有边,则他们交点 为1 ,否则为0。当然,如果是一副边有权值的图,交点存储的是他们边的权值。
有1必有回1则为无向图,有1未必有回1则为有向图

const int MAX_VERTEX = 3;//数据的数量struct ArrayGraph{    vector<string>vertexArr;//顶点元素数组    int arcArr[MAX_VERTEX][MAX_VERTEX];//链接弧二维数组};void ArrayGraph_init(ArrayGraph &pGraph);void ArrayGraph_create(ArrayGraph &pGraph);void ArrayGraph_show(ArrayGraph &pGraph);int main(){    ArrayGraph graph;    ArrayGraph_init(graph);    ArrayGraph_create(graph);    ArrayGraph_show(graph);    system("pause");    return 0;}void ArrayGraph_init(ArrayGraph & pGraph){    for (int i = 0; i < MAX_VERTEX; ++i)    {        pGraph.arcArr[i][i] = 0;    }}void ArrayGraph_create(ArrayGraph & pGraph){    for (int i = 0; i < MAX_VERTEX; ++i)    {        cout << "请输入第" << i + 1 << "个顶点值" << endl;        string strMsg;        cin >> strMsg;        pGraph.vertexArr.push_back(strMsg);    }    for (int i = 0; i < MAX_VERTEX; ++i)    {        for (int j = i + 1; j < MAX_VERTEX; ++j)        {            cout << "若元素" << pGraph.vertexArr[i] << "有指向" << pGraph.vertexArr[j] << "的弧,则输入1,否则输入0" << endl;            int IntMsg;            cin >> IntMsg;            pGraph.arcArr[i][j] = IntMsg;            cout << "若元素" << pGraph.vertexArr[j] << "有指向" << pGraph.vertexArr[i] << "的弧,则输入1,否则输入0" << endl;            cin >> IntMsg;            pGraph.arcArr[j][i] = IntMsg;        }    }}void ArrayGraph_show(ArrayGraph & pGraph){    cout << "顶点元素如下" << endl;    for (int i = 0; i < MAX_VERTEX; ++i)    {        cout << pGraph.vertexArr[i] << "  ";    }    cout << endl << endl;    cout << "矩阵如下" << endl << endl << "   ";    for (int i = 0; i < MAX_VERTEX; ++i)    {        cout << pGraph.vertexArr[i] << "  ";    }    cout << endl;    for (int i = 0; i < MAX_VERTEX; ++i)    {        cout << pGraph.vertexArr[i] << "  ";        for (int j = 0; j < MAX_VERTEX; ++j)        {            cout << pGraph.arcArr[i][j] << "  ";        }        cout << endl;    }    cout << endl;}
原创粉丝点击