- 问题描述
在3×3的方格上分别放置1,2,3,4,5,6,7,8,9的八张排,初始状态为S0,目标状态为Sg,计算出从S0到Sg的方法。
- 代码及说明
/******************************************************************************
* 使用深度优先、广度优先和A*算法解决九宫问题
******************************************************************************/

#include
<
stdio.h
>
#include
<
iostream.h
>
#include
<
string
.h
>
#include
<
stdlib.h
>



#include
"
data.h
"
#include
"
queue.h
"
#include
"
stack.h
"
#include
"
link.h
"


#define
DEEPSEARCH 1
#define
WIDESEARCH 2
#define
ASTART 3

#define
SEARCHTYPE WIDESEARCH
//
定义使用广度优先


//
#define SHOWPROCESS
//
定义是否显示中间过程


class
SearchTree
{
private:
/***********************定义open表的数据类型************************/
#if SEARCHTYPE==WIDESEARCH
Queue open;
#elif SEARCHTYPE==DEEPSEARCH
Stack open;
#else
Link open;
#endif

Stack close;
public:
void init(); //初始化数据
void extend(); //扩展close表尾节点并添加进open表
void
moveToClose();
//
将open表的头节点移动到close表中
bool
success();
//
判断搜索是否成功
bool
openEmpty();
//
判断open表是否为空
void
showAnswer();
//
显示最终结果
}
;
void
SearchTree::showAnswer()
{
close.show();
}

bool
SearchTree::openEmpty()
{
return open.empty();
}


void
SearchTree::extend()
{
DATATYPE temp[LINE][ROW],buf[LINE][ROW];
Data *pid;
int n,m;
pid=close.getTop(*buf); //将close表的最后一项记录复制到buf中
for(n=0;n<LINE;n++)
for(m=0;m<ROW;m++)
if(buf[n][m]==0)//寻找buf中0所在的位置,0表示空格
goto L1;
L1:

memcpy(temp,buf,DATASIZE*sizeof(DATATYPE));
if(n!=0){ //空格上移
temp[n][m]=temp[n-1][m];
temp[n-1][m]=0;
if(close.exist(*temp)==false) open.push(*temp,&pid);
#ifdef SHOWPROCESS //宏定义,决定时候输出中间过程
cout<<"move below data to open table:"<<endl;
showElement(*temp);
getchar();
#endif
}


memcpy(temp,buf,DATASIZE*sizeof(DATATYPE));
if(n!=2){ //空格下移
temp[n][m]=temp[n+1][m];
temp[n+1][m]=0;
if(close.exist(*temp)==false) open.push(*temp,&pid);
#ifdef SHOWPROCESS
cout<<"move below data to open table:"<<endl;
showElement(*temp);
getchar();
#endif
}
memcpy(temp,buf,DATASIZE*sizeof(DATATYPE));
if(m!=0){ //空格左移
temp[n][m]=temp[n][m-1];
temp[n][m-1]=0;
if(close.exist(*temp)==false) open.push(*temp,&pid);
#ifdef SHOWPROCESS
cout<<"move below data to open table:"<<endl;
showElement(*temp);
getchar();
#endif
}
memcpy(temp,buf,DATASIZE*sizeof(DATATYPE));
if(m!=2){ //空格右移
temp[n][m]=temp[n][m+1];
temp[n][m+1]=0;
if(close.exist(*temp)==false) open.push(*temp,&pid);
#ifdef SHOWPROCESS
cout<<"move below data to open table:"<<endl;
showElement(*temp);
getchar();
#endif
}



该博客通过C++代码详细解释了如何使用深度优先、广度优先和A*算法来解决经典的九宫问题。通过初始化数据,扩展搜索路径并判断搜索状态,最终展示解决方案。

最低0.47元/天 解锁文章
1704





