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

数据结构-图-存储

邻接矩阵

存储如下图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;
}

运行效果

相关推荐
m0_547486661 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr1 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_31 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Jasmine_llq1 天前
《P11967 [GESP202503 八级] 割裂》
邻接表·倍增求 lca(最近公共祖先)·树上点差分(树上差分)·深度优先搜索 dfs·路径提取·倍增 lca 算法
All for pursuit.1 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.1 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣1 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9921 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水2 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1012 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质