算法复习:图(邻接矩阵和邻接表)

邻接矩阵

#include <iostream>
using namespace std;
const int N = 520,INF=0x3f3f3f3f;
int n,m;
int g[N][N];
void init()
{
	for(int i = 1;i <=n;i++)
		for(int j = 1;j <= n;j++)
			if(i == j) g[i][j] = 0;
			else g[i][j] = INF;
}
// 5 5
// 1 2 3
// 2 4 2
// 4 5 3
// 1 3 4
// 3 4 1
int main()
{
	cin>>n>>m;
	init();
	while(m--)
	{
		int x,y,w;
		cin>>x>>y>>w;
		g[x][y] = min(g[x][y],w);//重边
	}
	for(int i = 1;i <= n;i++)
	{
		for(int j = 1;j <= n;j++)
			cout<<g[i][j]<<" ";
		cout<<endl;
	}
	return 0;
}

邻接表

#include <bits/stdc++.h>
using namespace std;
const int N = 520,M = 520;
int n,m,head[N],idx; //head[N] 表示头节点 ,idx表示边的索引
struct{
	int to,next,w;//to表示指向的节点,next表示下一条边,w表示权重
}e[M];
void init()
{
	memset(head,-1,sizeof(head));
	idx = 1;
}
void add_mul(int a,int b,int w)
{
	e[idx].to =  b;
	e[idx].w = w;
	e[idx].next = head[a];//头插法
	head[a] = idx;
	idx ++;
}
bool vis[N];
void dfs(int now)
{
	vis[now] = true;
	for(int i = head[now];i != -1;i = e[i].next)
	{
		int to = e[i].to;
		int w = e[i].w;
		printf("%d->%d(%d)",now,to,w);
		if(vis[to]) continue;
		dfs(to);
	}
}
queue<int>Q;
void bfs(int now)
{
	Q.push(now);
	while(!Q.empty())
	{
		int i = Q.front();
		Q.pop();
		vis[i] = true;
		for(int j = head[i];j != -1;j = e[j].next)
		{
			int to = e[j].to;
			int w = e[j].w;
			if(vis[to]) continue;
			printf("%d->%d(%d)",i,to,w);
			vis[to] = true;
			Q.push(to);
		}
	}
}
int main()
{
	cin >> n >> m;
	init();
	while(m--)
	{
		int from,to,w;
		cin >> from >> to >> w;
		add_mul(from,to,w);
	}
	bfs(1);
	cout<<endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值