数据结构总结之bfs
来源:互联网 发布:hadoop 处理数据 编辑:程序博客网 时间:2024/05/16 14:44
1.模板题uva439的模板:
其实就是用queue,结构体node,vis数组,步数(路径)都可以放在结构体里面
#include<iostream>#include<cstring>#include<string>#include<queue>#include<cmath>using namespace std;const int MAXN = 8 + 2;struct Node{ int x, y, d; Node() {} Node(int x,int y,int d=0):x(x),y(y),d(d) {}};int vis[MAXN][MAXN];Node start, dest;bool isvalid(int x, int y){ return x > 0 && x < 9 && y > 0 && y < 9;}int dir[8][2]= {-2,-1,-2,1,-1,-2,-1,2,1,-2,2,-1,2,1,1,2};void bfs(){ queue<Node> q; q.push(start); while (!q.empty()) { Node horse = q.front(); q.pop(); for(int i=0; i<8; i++) { int x = horse.x + dir[i][0]; int y = horse.y + dir[i][1]; if ( isvalid(x, y) && !vis[x][y]) { if (dest.x == x && dest.y == y) { dest.d = horse.d + 1; return; } vis[x][y] = 1; q.push(Node(x, y, horse.d +1)); } } }}int main(){ string s1, s2; while (cin >> s1 >> s2) { memset(vis, 0, sizeof(vis)); start.x = s1[0] - 'a' + 1; start.y = s1[1] - '0'; start.d = 0;//横纵都从1开始 dest.x = s2[0] - 'a' + 1; dest.y = s2[1] - '0'; dest.d = 0; vis[start.x][start.y] = 1; bfs(); cout << "To get from "<<s1<<" to "<<s2<<" takes "<<dest.d<<" knight moves.\n"; } return 0;}
2.bfs适用于“以层计数”的递归结构,如:uva417
#include <iostream>#include <map>#include <stdio.h>#include <string>#include <queue>using namespace std;map<string,int> m;queue<string> q;int cnt;char ch[26];void bfs(){ q.push(""); while(!q.empty()) { string v=q.front(); q.pop(); int t; if(v.length()) t=*(v.end()-1)-'a'+1; else t=0; for(int i=t;i<26;i++) { string u=v+ch[i]; if(u.length()==6) return ; q.push(u); m[u]=++cnt; } }}int main(){ ch[0]='a'; for(int i=1;i<26;i++) ch[i]=ch[i-1]+1; bfs(); char r[6]; while(~scanf("%s",r)) { if(m.count(r)) printf("%d\n",m[r]); else printf("0\n"); } return 0;}
阅读全文
0 0
- 数据结构总结之bfs
- 总结之bfs,dfs
- 数据结构之DFS与BFS实现
- 数据结构之BFS(邻接表版)
- [数据结构]之调研总结
- 数据结构之查找总结
- 【数据结构之宏观总结 】
- 数据结构总结之map
- 数据结构总结之二分
- 数据结构总结之dfs
- 数据结构总结之队列
- 数据结构总结之树
- 数据结构总结之KMP
- 数据结构总结之lca
- 大话数据结构之第一章数据结构绪论总结
- 数据结构作业 迷宫问题 模拟 之基础的BFS DFS
- 【数据结构】图的遍历之DFS和BFS
- 数据结构基础 图的遍历(二) 之 BFS
- JVM(一):java内存区域
- 写给我即将毕业的研究生
- Mysql 操作
- Swing 的按钮循环添加点击事件并被公共访问
- 剑指offer系列(7)——旋转数组的最小数字
- 数据结构总结之bfs
- Unity鼠标控制物体360°旋转和点击移动
- SpringMVC 拦截器遇到浏览器请求/favicon.ico被拦截导致触发session失效问题的处理办法
- ListView 通用适配器
- 软银中国负责人 潘政荣:80%的创业者没有想清楚要做什么
- [ 随机增量法 ] BZOJ1336 && 1337 && 2823
- JS中点击事件冒泡解析
- 程序员,你还要迷茫多久?
- 年底福利来了,一次性送10本书,就是这么暴力!