无向图的深度搜索和广度搜索

学习图的第一步 :

#define MAXNODE 40  // 千万不要加 ;
#define NIL 999
#define INFI 9999999

#include <iostream>
#include <queue>
using namespace std;

struct arcnode {
 int vertex;
 int weight;
 struct arcnode * nextarc;
};

typedef struct {
 int vertex;
 struct arcnode * firstarc;
} vernode;

queue<int> gqueue;
typedef vernode adjlist[MAXNODE];
adjlist graph;
void (*p) (int k, int *);

void inite() {
 for( int i=1; i<=MAXNODE; i++) {
  graph[i].vertex=i;
  graph[i].firstarc=NULL;
 }
}

void insert( int start, int end, int weight=0) {
 arcnode * p=new arcnode;
 p->vertex=end;
 p->weight=weight;
 p->nextarc=graph[start].firstarc;
 graph[start].firstarc=p;
// 因为是无向图,所以需要添加两次!!!
 arcnode *q=new arcnode;
 q->vertex=start;
 q->weight=weight;
 q->nextarc=graph[end].firstarc;
 graph[end].firstarc=q;
}

void dfs( int k, int visited[] ) {
 arcnode *p;
 int w;
 visited[k]=1;
 cout<<graph[k].vertex<<"  ";
 p=graph[k].firstarc;
 while( p!=NULL ) {
  w=p->vertex;
  if( visited[w]==0 )
   dfs( w, visited);
  p=p->nextarc;
 }
}


void bfs( int k, int visited[] ) {
 int w;
 arcnode *p;
 visited[k]=1;
 cout<<k<<"  ";
 gqueue.push(k);
 while( !gqueue.empty() ) {
  w=gqueue.front();
  gqueue.pop();
  p=graph[w].firstarc;
  while( p!=NULL ) {
   if( visited[p->vertex]==0 ) {
    visited[p->vertex]=1;
    cout<<p->vertex<<"  ";
    gqueue.push(p->vertex);
   }
   p=p->nextarc;
  }
 }
}

void travel( int n , void (*p)( int , int *)) {   // 使用函数指针
 int i, visited[MAXNODE];
 for( i=1; i<=n; i++)
  visited[i]=0;
 for( i=1; i<=n; i++)
  if( visited[i]==0)
   (*p)( i,visited);
}

void print( int n) {
 arcnode *q;
 int i;
 cout<<"输出无向图的邻接链表示:"<<endl;
 for(i=1;i<=n;i++) {
  cout<<'/t'<<i<<"/t";
  cout<<graph[i].vertex<<"->";
  q=graph[i].firstarc;
  while(q!=NULL) {
   cout<<q->vertex<<"->";
   q=q->nextarc;
  }
  cout<<endl;
 }
 }

int main() {
 inite();
 freopen("D://in.txt", "r", stdin);
 int n, e, start, end, weight;
 cout<<"输入顶点的个数 "<<endl;
 cin>>n;
 cout<<"输入边的条数 "<<endl;
 cin>>e;
 for( int i=1; i<=e; i++) {
  cout<<"输入第 "<<i<<" 边的起点,终点,权值";
  cin>>start>>end>>weight;
  cout<<endl;
  insert(start,end,weight);
 }
 cout<<"无向图的链接表表示为: "<<endl;
 print( n);
 cout<<"广度搜索为: "<<endl;
 travel(n, bfs );
 cout<<endl;
 cout<<"深度搜索为: "<<endl;
 travel(n, dfs );
 cout<<endl;
 cin.get();
 return 0;
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值