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

数据结构-图-存储

邻接矩阵

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

运行效果

相关推荐
czxyvX1 小时前
016-二叉搜索树(C++实现)
开发语言·数据结构·c++
执着2591 小时前
力扣hot100 - 94、二叉树的中序遍历
数据结构·算法·leetcode
-dzk-1 小时前
【代码随想录】LC 707.设计链表
数据结构·c++·算法·链表
you-_ling2 小时前
数据结构:3.栈和队列
数据结构
梵刹古音3 小时前
【C语言】 递归函数
c语言·数据结构·算法
代码游侠4 小时前
C语言核心概念复习(二)
c语言·开发语言·数据结构·笔记·学习·算法
you-_ling4 小时前
数据结构:5.哈希表
数据结构·散列表
鲨辣椒100865 小时前
二叉树代码变现——递归函数实现深度遍历
数据结构
2301_810730105 小时前
python第四次作业
数据结构·python·算法
春栀怡铃声5 小时前
认识二叉树~
c语言·数据结构·经验分享·c·编译