预备知识:图的表示

邻接矩阵

在这里插入图片描述

//
// Created by YaMiwan on 2020-05-07.
//


#include <iostream>

using namespace std;


int main(){
    const int MAX_N = 5;  // 一共5个顶点
    int Graph[MAX_N][MAX_N] = {0};  // 使用邻接矩阵表示
    Graph[0][2] = 1;  // 将图连通,且不带权
    Graph[0][4] = 1;  // 一般用邻接矩阵表示稠密图
    Graph[1][0] = 1;
    Graph[1][2] = 1;
    Graph[2][3] = 1;
    Graph[3][4] = 1;
    Graph[4][3] = 1;
    printf("Graph:\n");
    for (int i = 0; i < MAX_N; i++){
        for (int j = 0; j < MAX_N; j++){
            printf("%d ", Graph[i][j]);
        }
        printf("\n");
    }
    return 0;
}
0 0 1 0 1
1 0 1 0 0
0 0 0 1 0
0 0 0 0 1
0 0 0 1 0

邻接表

//
// Created by YaMiwan on 2020-05-07.
//


#include <iostream>
#include <vector>

using namespace std;


struct GraphNode {  // 图的邻接表数据结构
    int label;  // 图的顶点的值
    vector<GraphNode *> neighbors;  // 相邻节点指针数组

    GraphNode(int x) : label(x) {};
};

int main() {
    const int MAX_N = 5;
    GraphNode *Graph[MAX_N];
    for (int i = 0; i < MAX_N; i++) {
        Graph[i] = new GraphNode(i);  //给顶点赋值
    }
    Graph[0]->neighbors.push_back(Graph[2]);  // 添加边
    Graph[0]->neighbors.push_back(Graph[4]);
    Graph[1]->neighbors.push_back(Graph[0]);
    Graph[1]->neighbors.push_back(Graph[2]);
    Graph[2]->neighbors.push_back(Graph[3]);
    Graph[3]->neighbors.push_back(Graph[4]);
    Graph[4]->neighbors.push_back(Graph[3]);

    cout << "Graph:" << endl;
    for (int i = 0; i < MAX_N; i++) {
        cout << "Label:";
        for (int j = 0; j < Graph[i]->neighbors.size(); j++) {
            cout << Graph[i]->neighbors[j]->label << " ";
        }
        cout << endl;
    }
    for (int i = 0; i < MAX_N; i++) {
        delete Graph[i];  // 删除图节点
    }
    return 0;
}
Graph:
Label:2 4
Label:0 2
Label:3
Label:4
Label:3
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值