8 puzzle 问题
输入按照以下格式:
i0 i3 i6
i1 i4 i7
i2 i5 i8
例如:
2 3 5
1 8 6
7 0 4
程序通过移动数字0完成整个过程,然后返回数字零的所有移动过程(l r r u d d l)
运行后结果是:
1 2 3
8 0 4
7 6 5
请教大侠们,我用数组将原始数据读入后,想用队列实现breadth-first算法,可是如何将移动前的步骤,和
移动后的步骤记录下来。待整个算法运行结束后好返回所有步骤。
是否可以将函数压入,队列或堆栈?
以下是我读入数据得程序,进行不下去了,忘哪位略指点1,2,不胜感激
#include<iostream>
using namespace std;
int i[9];
int position;
void input();
void print();
void u(int k);
void d(int k);
void l(int k);
void r(int k);
void breadth_first();
void depth_first();
void a_start();
void input()
{
int k;
cout<<"input 9 numbers (0,1.....8) following this position:"<<endl;
cout<<"i0 i3 i6"<<endl;
cout<<"i1 i4 i7"<<endl;
cout<<"i2 i5 i8"<<endl<<endl;
cout<<"i0....i8:";
cin>>i[0]>>i[1]>>i[2]>>i[3]>>i[4]>>i[5]>>i[6]>>i[7]>>i[8];
cout<<endl;
// cout<<i[0]<<" "<<i[3]<<" "<<i[6]<<endl;
// cout<<i[1]<<" "<<i[4]<<" "<<i[7]<<endl;
// cout<<i[2]<<" "<<i[5]<<" "<<i[8]<<endl<<endl;
for(k=0;k<9;k++)
{
if(i[k]==0)
position=k;
}
}
void print()
{
cout<<i[0]<<" "<<i[3]<<" "<<i[6]<<endl;
cout<<i[1]<<" "<<i[4]<<" "<<i[7]<<endl;
cout<<i[2]<<" "<<i[5]<<" "<<i[8]<<endl<<endl;
}
void u(int k) //是否要在每个函数中建立一个数组来保存移动前的原始数据
{
int temp;
temp=i[k];
i[k]=i[k-1];
i[k-1]=temp;
position=k-1;
}
void d(int k)
{
int temp;
temp=i[k];
i[k]=i[k+1];
i[k+1]=temp;
position=k+1;
}
void l(int k)
{
int temp;
temp=i[k];
i[k]=i[k-3];
i[k-3]=temp;
position=k-3;
}
void r(int k)
{
int temp;
temp=i[k];
i[k]=i[k+3];
i[k+3]=temp;
position=k+3;
}