学习过A*算法后,通过计算出每个节点的f值,在把队列里的节点通过对f的大小进行排列。
f=h+g
g是已经走过的步数,h为还需要最少的步数。
#include<iostream>
using namespace std;
const int MAXX = 1000000;
struct Node
{
char tile[10];
int pos;
int parents;
int g,f;
int pre;
};
int cmp(const void*a, const void *b){
if ((*(Node*)a).f == (*(Node*)b).f)
return ((*(Node*)a).g == (*(Node*)b).g);
return ((*(Node*)a).f - (*(Node*)b).f);
}
int _move[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
char pre[4] = { 'r', 'l', 'd', 'u' };
Node qu[MAXX];
int front, tail,b;
char _start[10],_end[10]="12345678x";
void init(){
front = tail = 0;
qu[tail++].parents = -1;
strcpy(qu[0].tile, _start);
qu[0].pos = strchr(_start, 'x') - _start;
qu[0].g = 0;
b = 0;
}
int isexit(Node node){
for (int i = 0; i<tail; i++){
if (strcmp(qu[i].tile, node.tile) == 0) return 1;
}
return 0;
}
int getF(Node node){
int temp = 0;
for (int i = 0; i < 9; i++){
if (node.tile[i] != _end[i]) temp++;
}
return temp;
}
void show(Node temp){
if (temp.parents != 0){
show(qu[temp.parents]);
}
cout << pre[temp.pre];
}
void dfs(){
Node temp,now;
int x, y;
while (tail-front>0)
{
qsort(qu + front, tail - front, sizeof(Node), cmp);
now = qu[front++];
//找到答案
if (strcmp(now.tile, _end) == 0){
b = 1;
show(now);
cout << endl;
return;
}
temp.g = now.g + 1;
for (int i = 0; i < 4; i++){
strcpy(temp.tile, now.tile);
x = now.pos / 3 + _move[i][0];
y = now.pos % 3 + _move[i][1];
if (x < 0 || x >= 3 || y < 0 || y >= 3) continue;
temp.pos = x * 3 + y;
temp.tile[now.pos] = now.tile[temp.pos];
temp.tile[temp.pos] = 'x';
if (isexit(temp)){
continue;
}
temp.parents = front - 1;
temp.pre = i;
temp.f = temp.g+getF(temp);
qu[tail++] = temp;
}
}
}
int main(){
char str[50];
while (gets(str)){
int ans= 0;
for (int i = 0; str[i]; i++){
if (str[i] != ' ') _start[ans++] = str[i];
}
if (strcmp(_start, _end) == 0) cout << "lr" << endl;
else
{
init();
dfs();
if (!b) cout << "unsolvable" << endl;
}
}
return 0;
}