邻接表(链式前向星和更常用的数组模拟)和dfs,bfs搜索图

链式前向星

#include <bits/stdc++.h>
using namespace std;
const int N = 1005;
const int M = 2005;
struct Node
{
    int v, w, nxt;
} node[M];
int cnt, head[N];
// head值和node下标均用于存储边序号,head的下标是结点序号
void addedge(int u, int v, int w)
{
    node[cnt].v = v;
    node[cnt].w = w;
    node[cnt].nxt = head[u]; // 把u点指向的边的序号赋值给当前边的nxt
    head[u] = cnt++;         // 把这条边的序号赋值给head
}
int main()
{
    memset(head, -1, sizeof(head)); // 初始化为-1
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int u, v, w;
        cin >> u >> v >> w;
        addedge(u, v, w);
    }
    for(int i=1;i<=n;i++){
        for(int j=head[i];j!=-1;j=node[j].nxt)cout<<node[j].v<<" value:"<<node[j].w<<"  ";
        cout<<endl;
    }
    // system("pause");
    return 0;
}

更普遍的处理:模拟链表和对应的dfs

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5;
int head[N],e[N],nxt[N],value[N],idx;
int n,m;
void addedge(int u,int v,int w){
    e[idx]=v;
    value[idx]=w;
    nxt[idx]=head[u];
    head[u]=idx++;
}


void visit(int u){
    cout<<u;//输出访问点的路径
}
bool visited[N];
void dfs(int u){//传入的是某个点的序号
    visit(u);
    visited[u]=true;
    for(int i=head[u];i!=-1;i=nxt[i]){
        int j=e[i];//下一个点的序号
        if(visited[j]==false){
            dfs(j);
        }
    }
}

int main(){
    memset(head,-1,sizeof(head));

    cin>>n>>m;

    for(int i=1;i<=m;i++){
        int u,v,w;
        cin>>u>>v>>w;
        addedge(u,v,w);
        addedge(v,u,w);
    }
    
    for(int i=1;i<=n;i++){
        for(int j=head[i];j!=-1;j=nxt[j]){
            cout<<e[j]<<":"<<value[j]<<"->";
        }
        cout<<endl;
    }

    dfs(1);//从1节点开始搜
    system("pause");
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值