广搜与深搜
来源:互联网 发布:程序员的爱情代码 编辑:程序博客网 时间:2024/04/28 11:43
广度优先搜索
#include <iostream>#include <string.h>#include <stdio.h>#include <queue>using namespace std;const int N = 10005;bool vis[N];int cnt,n,m;queue<int> Q;int head[N],to[N],next[N],w[N];int T[N],ct;void Init(){ ct = 0; cnt = 0; memset(head,-1,sizeof(head));}void add(int u,int v,int c){ to[cnt] = v; w[cnt] = c; next[cnt] = head[u]; head[u] = cnt++; to[cnt] = u; w[cnt] = c; next[cnt] = head[v]; head[v] = cnt++;}void BFS(int s){ memset(vis,false,sizeof(vis)); while(!Q.empty()) Q.pop(); vis[s] = true; T[ct++] = s; Q.push(s); while(!Q.empty()) { int u = Q.front(); Q.pop(); for(int i=head[u]; ~i; i=next[i]) { int v = to[i]; if(!vis[v]) { vis[v] = true; T[ct++] = v; Q.push(v); } } }}int main(){ int n; while(~scanf("%d",&n)) { Init(); for(int i=1;i<=n;i++) { int u,v; scanf("%d%d",&u,&v); add(u,v,1); } BFS(1); for(int i=0;i<ct;i++) cout<<T[i]<<" "; puts(""); } return 0;}
深度优先遍历
#include <iostream>#include <string.h>#include <stdio.h>#include <queue>using namespace std;const int N = 10005;bool vis[N];int cnt,n,m;int head[N],to[N],next[N],w[N];int T[N],ct;void Init(){ ct = 0; cnt = 0; memset(head,-1,sizeof(head)); memset(vis,false,sizeof(vis));}void add(int u,int v,int c){ to[cnt] = v; w[cnt] = c; next[cnt] = head[u]; head[u] = cnt++; to[cnt] = u; w[cnt] = c; next[cnt] = head[v]; head[v] = cnt++;}void DFS(int s){ vis[s] = true; T[ct++] = s; for(int i=head[s]; ~i; i=next[i]) { int v = to[i]; if(!vis[v]) { printf("%d, %d\n",s,v); DFS(v); } }}int main(){ int n; while(~scanf("%d",&n)) { Init(); for(int i=1;i<=n;i++) { int u,v; scanf("%d%d",&u,&v); add(u,v,1); } DFS(1); for(int i=0;i<ct;i++) cout<<T[i]<<" "; puts(""); } return 0;}
- 广搜与深搜
- 深搜与广搜
- 深搜与广搜
- 广搜与深搜
- 深搜与广搜
- 广搜与深搜的区别
- 图的深搜与广搜
- 图的深搜与广搜
- 深搜与广搜的特点
- 深搜与广搜以及例题
- 广搜与深搜实现
- 深搜与广搜的区别
- 深搜算法与广搜算法总结
- 广搜与深搜的小区别
- 邻接表的深搜与广搜遍历
- 二叉树的深搜与广搜
- 【POJ2386】Lake Counting(深搜与广搜)
- C.就来谈谈深搜与广搜
- JMX学习体会(只是本人的文章从JAVAEYE搬到这来)
- svn 状态信息
- hibernate many-to-many(单向和双向)--->(annotation和xml文件两种形式)
- 从dll中导出类
- FRU 121SS080C/ASM BAHL00L6S
- 广搜与深搜
- java中无符号类型处理
- svn 用法
- CocoaAsyncSocket学习
- PERL学习
- androidpn(小强版)异常收集
- Android通过setContentView切换页面示例(华为U9200下测试,最短切换耗时2ms,稳定在6-8ms)
- 开源库ASIHTTPRequest使用介绍
- POJ 1742:Coins——单调队列优化的多重背包