求不带权无向连通图中距离给定节点最远的节点

解题思路

首先确定使用图的BFS,因为BFS是由近到远一点点蔓延过去的。所以队列中的最后一个节点一定是距离给定节点最远的点。

代码实现

  • vector模拟邻接表代码
#include <iostream>
#include <vector>
#include <queue>

using namespace std;
const int MAXN = 2000;
int vis[MAXN];

//采用vector模拟图的邻接表存储方法
//求图中离给定节点最远的节点
//思路:bfs中最后的节点就是离给定节点最远的节点
struct edge{
    int to;

    edge(int t)
    {
        to = t;
    }
};

vector <edge> G[MAXN];

void add_edge(int from, int to)
{
    G[from].push_back(edge{to});
    G[to].push_back(edge{from});
}

int bfs(int s)
{
    queue<int> que;
    int maxi = s;

    que.push(s);
    vis[s] = 1;
    
    while (!que.empty())
    {
        maxi = que.front();
        que.pop();

        for (int i=0; i<G[maxi].size(); i++)
        {
            if (!vis[G[maxi][i].to])
            {
                vis[G[maxi][i].to] = 1;
                que.push(G[maxi][i].to);
            }
        }
    }

    return maxi;
}

int main()
{
    int n;

    cin >> n;

    for (int i=0; i<n; i++)
    {
        int from, to;
        
        cin >> from >> to;
        add_edge(from, to);
    }

    cout << bfs(0) << endl;

    return 0;
}
  • 邻接表代码
#include <iostream>
#include <vector>
#include <queue>

using namespace std;
const int MAXN = 2000;
int vis[MAXN];

struct ArcNode {
    int adjvex;
    ArcNode *nextarc;
};

struct vNode {
    char data;
    ArcNode *firstarc;
};

struct Graph {
    vNode adjlist[MAXN];
    int n, e;
};

void create_Graph(Graph *&G, int n)
{
    int from, to;

    for (int i=0; i<n; i++)
    {
        cin >> from >> to;

        ArcNode *s = new ArcNode;
        s->adjvex = to;
        s->nextarc = G->adjlist[from].firstarc;
        G->adjlist[from].firstarc = s;
    }
}

int bfs(Graph *G, int s)
{
    queue<int> que;
    int maxi = s;
    que.push(s);
    vis[s] = 1;

    while (!que.empty())
    {
        ArcNode *p = G->adjlist[que.front()].firstarc;
        maxi = que.front();
        que.pop();

        while (p)
        {
            if (!vis[p->adjvex])
            {
                vis[p->adjvex] = 1;
                que.push(p->adjvex);
            }

            p = p->nextarc;
        }
    }

    return maxi;
}

int main()
{
    Graph *G = new Graph;
    int n;
    
    cin >> n;
    create_Graph(G, n);
    cout << bfs(G, 0) << endl;

    return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值