您的位置:首页 > 其它

[Uva 10085] The most distant state (BFS)

2014-11-28 01:57 459 查看
题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1026

题目大意:就是说给你一个8数码,问你能够达到的距离最远的状态是什么。

刚开始以为只要顺着一边走就行了,后来发现这样走可能最远到达的状态也能通过其他方式到达。

在这里WA了好多次。

应该把所有可能出现的情况全都枚举出来,然后判重。。

UVA也真是慢。。4s的代码跑了快4分钟。。。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <map>
#include <set>
#include <queue>
#include <string>
using namespace std;
typedef unsigned long long ull;

const int B = 10;

struct Node{
int status[3][3];
int h;
int x,y;
string route;
};

int T;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};

int main(){
scanf("%d",&T);
for(int t=1;t<=T;t++){
Node s;
s.h = 0;
set<int> se;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
scanf("%d",&s.status[i][j]);
s.h = s.h*10+s.status[i][j];
if( s.status[i][j] == 0){
s.x = i; s.y = j;
}
}
}
se.insert(s.h);
//        printf("%d\n",s.h);
s.route = "";
queue<Node> q;
q.push(s);
Node ans = s;
bool fl = true;
while(!q.empty()){
Node tn = q.front(); q.pop();
if( fl || ans.route.size()<tn.route.size()) ans = tn;
for(int i=0;i<4;i++){
Node t = tn;
int dx = t.x+dir[i][0], dy = t.y+dir[i][1];
if( dx<=2&&dx>=0&&dy<=2&&dy>=0 ){
swap(t.status[tn.x][tn.y],t.status[dx][dy]);
t.x = dx; t.y = dy;
int tt = 0;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
tt = tt*B+t.status[i][j];
}
}
t.h = tt;

if( i==0 ) t.route = tn.route+"D";
else if( i==1 ) t.route = tn.route+"U";
else if( i==2 ) t.route = tn.route+"R";
else if( i==3 ) t.route = tn.route+"L";
if( se.find(tt)==se.end() ){
se.insert(tt);
q.push(t);
}
}
}
}
printf("Puzzle #%d\n",t);
for(int i=0;i<3;i++) for(int j=0;j<3;j++){
printf(j==2?"%d\n":"%d ",ans.status[i][j]);
}
puts(ans.route.c_str());
puts("");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: