Chris_kxt 2018-11-21 15:37 采纳率: 100%
浏览 1045
已结题

C++语言编程 无向图判断节点存在路径

创建无向图邻接矩阵G,实现一个函数isPath(v, w),其中v和w是图中的顶点,检查两个节点之间是否有路径。找到的路径将作为整数序列(节点值)打印到文本文件中。

  • 写回答

1条回答 默认 最新

  • I_love_csdn_verymuch 2018-11-24 02:13
    关注
     #include<bits/stdc++.h>
    using namespace std;
    int f[1000][1000];
    int h[1000];
    vector<int>path;
    int n,m;
    bool pathed=0;
    void isPath(int now,int end){
        if(now==end){
            pathed=1;
            return ;
        }
        h[now]=1;
        for(int i=1;i<=n;i++){
            if(f[now][i]&&!h[i]){
                path.push_back(i);
                isPath(i,end);
                if(pathed)return ;
                path.pop_back();
            }
        }
    }
    int main(){
        ios::sync_with_stdio(false);
        cin.tie(0);
        cin>>n>>m;
        for(int i=1;i<=m;i++){
            int x,y;
            cin>>x>>y;
            f[x][y]=1;
            f[y][x]=1;
        }
        int x,y;
        cin>>x>>y;
        path.push_back(x);
        isPath(x,y);
        if(pathed){
            cout<<path[0];
            for(int i=1;i<path.size();i++){
                cout<<"->"<<path[i];
            }
            cout<<endl;
        }else{
            cout<<"No path between "<<x<<" and "<<y<<" !"<<endl;
        }
        return 0;
    }
    

    图片说明
    图片说明
    图片说明
    如有问题,请私聊QQ:3143664703

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型