hdu1195 Open the Lock (BFS)
来源:互联网 发布:天然子结构知乎 编辑:程序博客网 时间:2024/04/27 15:43
题意:给出两个4位的数字,都由1~9组成,要求经过一系列的操作将第一个数字变为第二个数字。操作有两种,
第一种:选择一位加上或减去1,9+1=1,1-1=9。
第二种:交换相邻的两位。第一位和第四位不相邻。
做法:简单bfs
代码:
#include <cstdio>#include <cstring>#include <algorithm>#include <iostream>#include <queue>#include <string>using namespace std;struct Node{int stat;int step;Node() {}Node(int a, int b) : stat(a), step(b) {}};int T;int start, end;queue<Node> q;int vis[11111];void push(Node nex) {if (!vis[nex.stat]) {vis[nex.stat] = 1;q.push(nex);}}int bfs() {memset(vis, 0, sizeof(vis));while (!q.empty()) q.pop();Node e = Node(start, 0);vis[start] = 1;q.push(e);while (!q.empty()) {e = q.front();q.pop();if (e.stat == end) return e.step;Node nex;int a = e.stat / 1000;int b = e.stat % 1000 / 100;int c = e.stat % 100 / 10;int d = e.stat % 10;if (a == 9) nex = Node(e.stat - 8000, e.step + 1);else nex = Node(e.stat + 1000, e.step + 1);push(nex);if (a == 1) nex = Node(e.stat + 8000, e.step + 1);else nex = Node(e.stat - 1000, e.step + 1);push(nex);if (b == 9) nex = Node(e.stat - 800, e.step + 1);else nex = Node(e.stat + 100, e.step + 1);push(nex);if (b == 1) nex = Node(e.stat + 800, e.step + 1);else nex = Node(e.stat - 100, e.step + 1);push(nex);if (c == 9) nex = Node(e.stat - 80, e.step + 1);else nex = Node(e.stat + 10, e.step + 1);push(nex);if (c == 1) nex = Node(e.stat + 80, e.step + 1);else nex = Node(e.stat - 10, e.step + 1);push(nex);if (d == 9) nex = Node(e.stat - 8, e.step + 1);else nex = Node(e.stat + 1, e.step + 1);push(nex);if (d == 1) nex = Node(e.stat + 8, e.step + 1);else nex = Node(e.stat - 1, e.step + 1);push(nex);nex = Node(b * 1000 + a * 100 + c * 10 + d, e.step + 1);push(nex);nex = Node(a * 1000 + c * 100 + b * 10 + d, e.step + 1);push(nex);nex = Node(a * 1000 + b * 100 + d * 10 + c, e.step + 1);push(nex);}return 0;}int main() {scanf("%d", &T);while (T--) {scanf("%d%d", &start, &end);int ans = bfs();printf("%d\n", ans);}return 0;}
0 0
- hdu1195 Open the Lock(BFS)
- HDU1195:Open the Lock(BFS)
- HDU1195:Open the Lock(BFS)
- hdu1195 Open the Lock (BFS)
- hdu1195 Open the Lock BFS 广搜
- hdu1195-Open the Lock-双向&&单向bfs
- hdu1195 Open the Lock(bfs水题)
- hdu1195 Open the Lock (bfs)
- hdu1195 Open the Lock
- hdu1195 Open the Lock
- hdu1195 Open the Lock
- hdu1195 Open the Lock
- hdu1195-Open the Lock
- HDU1195 Open the Lock
- HDU1195 Open the Lock
- hdu1195 Open the Lock
- HDU1195---Open the Lock
- HDU1195-Open the Lock
- 解决jquery升级1.6后checkbox的attr(checked)一直为undefined问题
- 关于彩信发送报告的研究
- 算法导论-----------------最优二叉搜索树
- linux JDK1.5 bin 安装
- 过滤器解决乱码问题
- hdu1195 Open the Lock (BFS)
- 复数
- java mail
- 黑马程序员——Java语言基础——02.java语言基础组成(3)函数
- 单例模式
- 第十六周项目四动态数组扩容
- 关于本博客的版权相关问题
- Android 网络通信框架Volley简介(Google IO 2013)
- 第十五周项目2-1