数据结构-图-存储-邻接矩阵-邻接表

数据结构-图-存储

邻接矩阵

存储如下图1,图2

图1

对应邻接矩阵

图2

cpp 复制代码
#include<bits/stdc++.h>
#define MAXN 1005
using namespace std;
int n;
int v[MAXN][MAXN]; 
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cin>>v[i][j];
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if(v[i][j]>0){
                cout<<"edge from point "<<i<<" to point "<<j
                <<" with length "<<v[i][j]<<"\n"; 
            }
        } 
    }
    return 0;
}

运行效果:

邻接表

存储示例代码:

cpp 复制代码
#include<bits/stdc++.h>
#define MAXN 1005
using namespace std;
struct edge{
    int to,cost;
};
int n,m;
vector<edge> p[MAXN];
int v[MAXN][MAXN];
int main(){
    cin>>n>>m;
    for(int i=1;i<=m;i++){
        int u,v,l;
        cin>>u>>v>>l;
        p[u].push_back((edge){v,l
        });
    }
    for(int i=1;i<=n;i++){
        for(int j=0;j<p[i].size();j++){
            v[i][p[i][j].to]=p[i][j].cost;
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            cout<<v[i][j]<<' ';
        }
        cout<<"\n";
    }
    return 0;
}

运行效果

相关推荐
Fanxt_Ja2 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
今后1232 天前
【数据结构】二叉树的概念
数据结构·二叉树
散1122 天前
01数据结构-01背包问题
数据结构
消失的旧时光-19432 天前
Kotlinx.serialization 使用讲解
android·数据结构·android jetpack
Gu_shiwww2 天前
数据结构8——双向链表
c语言·数据结构·python·链表·小白初步
苏小瀚3 天前
[数据结构] 排序
数据结构
睡不醒的kun3 天前
leetcode算法刷题的第三十四天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
吃着火锅x唱着歌3 天前
LeetCode 978.最长湍流子数组
数据结构·算法·leetcode
Whisper_long3 天前
【数据结构】深入理解堆:概念、应用与实现
数据结构
IAtlantiscsdn3 天前
Redis7底层数据结构解析
前端·数据结构·bootstrap