AOJ 0121: Seven Puzzle【BFS】
2024-08-27 18:38:53
From: AOJ 0121
思路:与前几题的bfs不同,这次的bfs没有明确的移动对象,看似任意一个数都可以当成对象移动。这时我们只需要抓住一个格子就行,比如我们把0作为移动对象,那么0在地图中漫游所有的格子得到的肯定就是问题的解空间。由于题目的输入是多个case,如果对每个case都运行一遍bfs就会TLE。这时我们祭出dp技能,只需要一次bfs就将解空间算出来,以后每个case只要到解空间中去找就行了。
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <queue>
using namespace std; map<string, int> dp;
int direction[4] = { 1, -1, 4, -4 }; //************************************
// Method: bfs
// FullName: bfs
// Access: public
// Returns: void
// Qualifier: 让0漫游整个字串
//************************************
void bfs()
{
queue<string> que;
que.push("01234567");
dp["01234567"] = 0;
while (!que.empty())
{
string now = que.front(); que.pop();
// p是'0'的位置
int p = 0;
for (int j = 0; j < 8; ++j)
{
if (now[j] == '0')
{
p = j;
break;
}
} for (int i = 0; i < 4; ++i)
{
int n = p + direction[i];
if (0 <= n && n < 8 &&
!(p == 3 && i == 0) && // 右上角不能再往右了
!(p == 4 && i == 1)) // 左下角不能再往左了
{
string next = now;
swap(next[p], next[n]);
if (dp.find(next) == dp.end())
{
dp[next] = dp[now] + 1;
que.push(next);
}
}
}
}
} int main()
{ bfs();
string line;
while (getline(cin, line))
{
line.erase(remove(line.begin(), line.end(), ' '), line.end());
cout << dp[line] << endl;
} return 0;
}
P.S. remove的用法与unique很接近,不能直接删除元素必须与erase结合使用
最新文章
- SQL Server 进制转换函数
- 支撑Java NIO 与 NodeJS的底层技术
- [知识点]KMP算法
- PHP date 格式化一个本地时间/日期
- 磁盘空间已满导致rabbitmq无法启动
- mongo语句优化分析
- MS SQL SERVER 数据库日志压缩方法与代码
- nginx学习之一
- Json 返回日期格式转换
- jQ的自定义插件
- Java常见问题3:周期之谜
- js:深闭包(范围:上)
- debugger 调试的一些经验
- 编写原生的Node.js模块
- Ajax同源和跨域
- nginx笔记6-总结
- 推荐几个牛逼的 IDEA 插件,还带动图!
- c语言:简单排序:冒泡排序法、选择排序法、插入排序法(待写)
- Python学习-终端字体高亮显示
- python动态函数hasattr,getattr,setattr,delattr
热门文章
- path操作
- [01] cocos2d-x开发环境搭建
- vim vi Ubuntu
- Bubble Cup 8 finals E. Spectator Riots (575E)
- JS阻止冒泡事件以及默认事件发生的简单方法
- c语言经典算法—求0—7 所能组成的奇数个数
- a标签产生间隙,<;a>; 包裹 <;img>; 产生 4px 间隙
- EXCEL 2010学习笔记 —— VLOOKUP函数 嵌套 MATCH 函数
- CentOS添加用户并加入sudo权限
- jemalloc在linux上从安装到使用