zoukankan      html  css  js  c++  java
  • DFS遍历图(链式邻接表实现)

     1 #include<iostream>
     2 #include<string.h>
     3 #include<stdlib.h>
     4 #include<stdio.h>
     5 using namespace std;
     6 struct Node{
     7     int num;
     8     Node * next;
     9 }node[1000];
    10 int vis[1000];
    11 void insert_link(Node *a,int value){
    12     while(a->next!=NULL){
    13         a=a->next;
    14     }
    15     Node *p=(Node *)malloc(sizeof(Node));
    16     p->num=value;
    17     p->next=NULL;
    18     a->next=p;
    19 }
    20 void DFS(Node  * node,int root){
    21     Node *p=node+root;
    22     int now=p->num;
    23     vis[now]=1;
    24     while(p->next!=NULL){
    25         int tmp=p->next->num;
    26         if(!vis[tmp]){
    27             DFS(node,tmp);
    28         }
    29         p=p->next;
    30     }
    31 }
    32 int main(){
    33     cout<<"下一行输入n和v表示图的顶点数和边数."<<endl;
    34     int n,v;
    35     cin>>n>>v; //输入顶点数n,边数v
    36     for(int i=1;i<=n;i++){ //初始化邻接表
    37         node[i].next=NULL;
    38         node[i].num=i;
    39     }
    40     printf("接下来 %d 行输入每条边的两个端点
    ",v);
    41     for(int i=0;i<v;i++){
    42         int x,y;
    43         cin>>x>>y; //输入边
    44         insert_link(node+x,y); //插入邻接表
    45         insert_link(node+y,x); //插入邻接表
    46     }
    47     memset(vis,0,sizeof(vis));
    48     DFS(node,1); //以node[1]为初始节点深度遍历图
    49     bool flag=true;
    50     for(int i=1;i<=n;i++){
    51         if(!vis[i]){
    52             flag=false;
    53         }
    54     }
    55     if(flag){
    56         cout<<"该图是无向连通图"<<endl;
    57     }else{
    58         cout<<"该图不是一个无向连通图"<<endl;
    59     }
    60     return 0;
    61 }
  • 相关阅读:
    2单表CRUD综合样例开发教程
    1代码表样例开发教程
    ProcessOn
    UniEAP Platform V5.0 Unable to compile class for JSP
    Message Unable to compile class for JSP
    UniEAP Platform V5.0建库
    UML_2_浅谈UML的概念和模型之UML九种图
    PPT鼠绘必须掌握的PPT绘图三大核心功能
    PPT添加节
    remap.config文件配置模板
  • 原文地址:https://www.cnblogs.com/ISGuXing/p/9075295.html
Copyright © 2011-2022 走看看