AOJ 0121 bfs
2016-07-26 08:00
411 查看
题意:
对于一个4X2的方格,有7个方片对应1–7,一个空格对应0,移动使得方格从左到右从上到下依次是01234567,问最短步数
题解:
使用map,map有两个数,以第一个数作为排序的标准,以第二个数作为该map对应的值
对于每一次的移动,直接抽象到一行来,注意条件的判断
注意:对于一行有空格且不知道长度的字符串,去空格的方法
对于一个4X2的方格,有7个方片对应1–7,一个空格对应0,移动使得方格从左到右从上到下依次是01234567,问最短步数
题解:
使用map,map有两个数,以第一个数作为排序的标准,以第二个数作为该map对应的值
map <string, int> dp;
对于每一次的移动,直接抽象到一行来,注意条件的判断
int direction[4] = { 1, -1, 4, -4 }; int n = index + direction[i]; //index是0的位置,括号分别表示右上角不能右移了和左下角不能左移了 if(n>=0&&n<8&&!(index==3&&i==0)&&!(index==4&&i==1))
注意:对于一行有空格且不知道长度的字符串,去空格的方法
string line; while (getline(cin, line)) { line.erase(remove(line.begin(), line.end(), ' '), line.end()); }
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<queue> #define pr(x) cout<<#x<<" "<<x; #define pl(x) cout<<#x<<" "<<x<<endl; #include<math.h> #include<algorithm> #include<set> #include<map> #include<unordered_set> using namespace std; map <string, int> dp; int direction[4] = { 1, -1, 4, -4 }; void bfs(){ queue <string >que; que.push("01234567"); dp["01234567"] = 0; while(que.size()){ string now = que.front(); que.pop(); int index = 0; for(int i = 0;i<8;i++){ if(now[i] =='0'){ index = i; break; } } for(int i =0;i<4;i++){ int n = index + direction[i]; if(n>=0&&n<8&&!(index==3&&i==0)&&!(index==4&&i==1)){ string next = now; swap(next ,next[index]); 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; }
相关文章推荐
- SVN学习笔记
- javascript学习笔记
- Wifi小车之 - 再探网页控制篇
- Android按钮单击事件的四种常用写法总结
- 查找链表的中间节点
- Java中访问权限控制
- ubuntu下code blocks安装全过程
- 递归算法
- iptables
- 设计模式(一)—单例模式
- 独家秘笈_block关键字的使用(通俗易懂+化繁为简)
- App Webview远程调试学习小记
- 关于静态变量,成员变量,静态方法,实例方法的用法及区别
- javascript中eval解析JSON字符串
- 除法
- Hygieia 部署指南(1)介绍篇
- Codevs 4600 [NOI2015]程序自动分析
- AOJ 0558 BFS
- Session入Redis
- python - 面向对象(二)