题目链接:http://poj.org/problem?id=1077
题意:八数码问题,求解输出一种可行的方案。
思路:很经典的bfs问题,可以用来练习双向bfs。
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;
#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod %100000007
const int dx[4] = {0,0,1,-1};
const int dy[4] = {1,-1,0,0};
const char way2[4] = {'l','r','u','d'}; //反向方向对应的走法
const char way1[4] = {'r','l','d','u'}; //正向方向对应的走法
struct node
{
int a[9];
int x,y;
}goal,q[370000],st;
map<int,int> p; //存状态
map<int,string> ans; //路径
int gethash(node &x)
{
int ans = 0;
rep(i,0,8) ans = ans * 10 + x.a[i];
return ans;
}
int getpos(int x,int y)
{
return x*3+y;
}
bool check(int x,int y)
{
return ( x >=0 && x < 3 && y >= 0 && y < 3 );
}
void init() //读入和初始化
{
ans.clear();
p.clear();
rep(i,0,8)
{
char c = getchar();
while( c == ' ' || c == '\n' ) c = getchar();
st.a[i] = (c=='x')?0:c-'0';
if ( st.a[i] == 0 )
{
st.x = i / 3;
st.y = i % 3;
}
}
rep(i,0,7) goal.a[i] = i + 1;
goal.a[8] = 0;
goal.x = goal.y = 2;
}
void bfs()
{
int head,tail;
head = tail = -1;
if ( memcmp(&st , &goal , sizeof(st)) == 0 )
{
puts("");
return;
}
tail++;
memcpy( &q[tail] , &st , sizeof(st) ); //初始状态入队
tail++;
memcpy( &q[tail] , &goal , sizeof(goal) ); //目标状态入队
p[gethash(st)] = 1; //正着拓展记为1
p[gethash(goal)] = 2;//反着拓展记为1
while( head < tail )
{
head++;
node &temp = q[head];
int xx,yy;
int temphash = gethash(temp);
rep(i,0,3)
{
xx = temp.x + dx[i];
yy = temp.y + dy[i];
if ( !check( xx , yy ) ) continue;
tail++;
node & next = q[tail];
memcpy( &next , &q[head] , sizeof(next) );
next.x = xx;
next.y = yy;
swap( next.a[ xx*3+yy ] , next.a[ temp.x*3 + temp.y ] );
//next为一个新的拓展
int hash = gethash(next);
if ( !p[hash] ) //如果next之前没有存在过
{
if ( p[temphash] == 1 )
ans[hash] = ans[temphash] + way1[i];
else
ans[hash] = way2[i] + ans[temphash]; //反着拓展要倒着叠加路径
p[hash] = p[temphash]; //记录路径并标记状态
}
else
{
if ( p[hash] != p[temphash] ) //如果队首拓展出来的状态和它的标记不一样,也就是正反搜索遇到了
{
if ( p[hash] == 1 )
cout<<ans[hash]<<way2[i]<<ans[temphash];//注意输出路径的顺序
else
cout<<ans[temphash]<<way1[i]<<ans[hash];
return;
}
else tail--;//这次新的拓展是一个重复的,不保留。
}
}
}
}
int main()
{
init();
bfs();
return 0;
}