uva-10085-搜索-最远状态的八数码

直接bfs即可,取最后一个状态

#include <iostream>
#include <stdio.h>
#include <string>
#include <map>
#include <queue> using namespace std; struct Dir
{
int x, y;
}; struct Node
{
int x, y;
string str = "";
string steps = "";
};
char st[] = { 'U', 'D', 'L', 'R' };
Dir dir[] = { { , - }, { , }, { -, }, { , } }; queue<Node> q;
const int N = ;
string ans = "";
string ansStep = ""; int index(int x, int y)
{
return y * + x;
} void bfs(map<string, int> repeatMaps)
{
while (!q.empty())
{
Node node = q.front();
q.pop();
int curZero = index(node.x, node.y);
string curStr = node.str;
for(int i = ; i < ; i++)
{
int nx = node.x + dir[i].x;
int ny = node.y + dir[i].y;
if(nx < || ny < || nx > || ny > )
continue;
//nextstr
string nextStr(curStr);
swap(nextStr[index(nx, ny)], nextStr[curZero]);
if(repeatMaps.find(nextStr) == repeatMaps.end())
{
//未重复
Node n;
n.str = nextStr;
n.x = nx;
n.y = ny;
n.steps = node.steps + st[i];
q.push(n);
ans = nextStr;
ansStep = n.steps;
repeatMaps[nextStr] = ;
}
}
}
} int main()
{
freopen("d://1.text", "r", stdin);
//3x3图
//目标图
int n;
cin >> n;
int t =;
while (n--)
{
if(t!=)
cout<<endl;
string str = "";
int k;
int x, y;
for(int i = ; i < ; i++)
for(int j = ; j < ; j++)
{
cin >> k;
str += k+'';
if(k == )
{
y = i;
x = j;
}
}
Node init;
init.steps = "";
init.str = str;
init.x = x;
init.y = y;
q.push(init);
map<string, int> repeatMaps;
repeatMaps[str] = ;
bfs(repeatMaps);
cout<<"Puzzle #"<<t<<endl;
for(int i=;i<;i++)
{
for(int j=;j<;j++)
{
if(j!=)
{
cout<<" ";
}
cout<<ans[i*+j];
}
cout<<endl;
}
cout << ansStep << endl;
++t;
}
return ;
}
上一篇:BZOJ1563: [NOI2009]诗人小G(决策单调性 前缀和 dp)


下一篇:[BZOJ1563][NOI2009]诗人小G(决策单调性优化DP)