您的位置:首页 > 其它

AOJ 0121 bfs

2016-07-26 08:00 411 查看
题意:

对于一个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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: