zoukankan      html  css  js  c++  java
  • bfs 邻接表(需要优化 可能会RE *【模板】)

    //---基于邻接表的bfs 
    
    #include <stdio.h> #include <string.h> #include <iostream> #include <string> #include <algorithm> #include <queue> using namespace std; struct node { int date; struct node *next; }*head[101], *tail[101]; void bfs(int s) { int flag=0; //标记输出,保证输出格式的正确的 bool vis[101]; memset(vis, false, sizeof(vis) ); queue<int>q; vis[s]=true; //标记起点访问 q.push(s); int cur; struct node *p; while( !q.empty() ) { cur=q.front(); if(flag==0) { printf("%d", cur ); flag=1; } else if(flag==1) { printf(" %d", cur ); } q.pop(); if( head[cur] ) //如果不空 { //开始遍历 p=head[cur]->next; while(p) { if(vis[p->date]==false) { q.push(p->date); vis[p->date]=true; } p=p->next; } } } printf(" "); } int main() { int t; cin>>t; int n, m, s; int u, v; int i; while(t--) { for(i=0; i<=100; i++) { head[i]=new struct node; head[i]->next = NULL; tail[i] = head[i]; } //邻接表的初始化 scanf("%d %d %d", &n, &m, &s) ; struct node *p, *q; for(i=0; i<m; i++) { scanf("%d %d", &u, &v ); p=new struct node; p->date=v; p->next=NULL; q=new struct node; q->date=u; q->next=NULL; tail[u]->next=p; tail[u]=p; tail[v]->next=q; tail[v]=q; } //建立邻接表 bfs(s); } return 0; }
  • 相关阅读:
    [转]跨语言通信方案比较
    C#三种定时器
    Java优化技巧
    websocket初探
    [转]远远走来一个绿茶婊
    赠与今年的大学毕业生-----------胡适
    HDU3068 回文串 Manacher算法
    OpenCV安装与配置
    tkinter事件机制
    哈夫曼压缩
  • 原文地址:https://www.cnblogs.com/yspworld/p/4275921.html
Copyright © 2011-2022 走看看