数据结构-图-存储-邻接矩阵-邻接表
数据结构-图-存储
邻接矩阵
存储如下图1,图2
图1

对应邻接矩阵

图2


代码示例:
#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; }
运行效果:

邻接表
存储示例代码:
#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; }
运行效果

作者:newcode 更多资源请关注纽扣编程微信公众号

从事机器人比赛、机器人等级考试、少儿scratch编程、信息学奥赛等研究学习

浙公网安备 33010602011771号