图的存储和遍历

1.图的存储

1.1 边的集合,其记录节点数,边数,每条边的起点和终点。这是最基本,最简单的方法,但是寻找邻居节点比较麻烦。需要转成邻接矩阵或者数组模拟邻接表

#include <bits/stdc++.h>
using namespace std;
#define N 1000
int n;//点的个数 
int m;//边的个数 
struct edge
{
	int u,v,w;//表示起点,终点和权值 
};
struct edge e[N];//边的集合 
int main()
{
	
	return 0;
}

1.2 邻接矩阵(二维数组),其记录任意两点之间是否有边。简单容易理解,但是有很多冗余数据,时间复杂度高。适合存储稠密图

#include <bits/stdc++.h>
using namespace std;
#define N 1000
int n;//点的个数 
int m;//边的个数 
int u,v,w;//起点,终点和权值。
int a[N][N];//邻接矩阵,其初始值全为0 
int main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		cin>>u>>v>>w;
		a[u][v]=w;
		a[v][u]=w;//无向图 
	}
	return 0;
}

1.3 数组模拟邻接表,其只记录有边的两点。复杂不容易理解,但无冗余数据,时间复杂度低。适合存储稀疏图

1.3.1普通数组实现

#include <bits/stdc++.h>
using namespace std;
#define N 1000
int n;//点的个数 
int m;//边的个数 
struct edge
{
	int u,v,w;//起点,终点和权值 
	int next;//记录下一条兄弟边	
};
struct edge e[N];//边的集合 
int id;//编号
int head[N];//链表头,每一个节点都有链表头
void insert(int u,int v,int w)
{
	//1.编号增一
	id++;
	//2.设置边的属性
	e[id].u=u;
	e[id].v=v;
	e[id].w=w;
	//3.插入 
	e[id].next=head[u];//头插法,先连后断
	head[u]=id;//更新链表头 
} 
int main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		int x,y,z;
		cin>>x>>y>>z;
		insert(x,y,z);
		insert(y,x,z);//无向边 
	}
	for(int i=1;i<=n;i++)
	{
		cout<<i<<":";
		for(int j=head[i];j!=0;j=e[j].next)
		{
			int kid=e[j].v;
			cout<<kid<<" ";
		}
		cout<<endl;
	} 
	return 0;
}
/*
4 5 
1 2 10
1 4 6
2 3 30
2 4 7
3 4 8
*/

1.3.2 动态数组实现

#include <bits/stdc++.h>
using namespace std;
#define N 1000
int n;//点的个数 
int m;//边的个数 
struct edge
{
	int v,w;//终点和权值 
};
vector<edge> G[N]; //动态数组存图 
void insert(int u,int v,int w)
{
	G[u].push_back({v,w}); 
} 
int main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		int x,y,z;
		cin>>x>>y>>z;
		insert(x,y,z);
		insert(y,x,z);//无向边 
	}
	for(int i=1;i<=n;i++)
	{
		cout<<i<<":";
		for(int j=0;j<G[i].size();j++)
		{
			int kid=G[i][j].v;
			cout<<kid<<" ";
		}
		cout<<endl;
	} 
	return 0;
}
/*
4 5 
1 2 10
1 4 6
2 3 30
2 4 7
3 4 8
*/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值