1 问题描述
拼图游戏,通常简单的也叫做八数码问题,就是解决如何通过移动有限的步数,从图的一个状态移动到另外一个状态,如下面的图所示:
2 问题解决的思路
一个简单的思路就是采取广度优先搜索算法,算法思路如下所示:
把起始状态图存储在哈希表中;
把起始状态加入队列当中;
循环判断当前状态是否等于结束状态
从队列中取出元素
寻找所有可以移动的操作,产生新状态X
若新位置状态X不在哈希表中
将X加入队列和哈希表
3 算法的实现
Puzzle.h
/*************************************************************************************/
/*"NITE and DAY" Puzzle */
/*************************************************************************************/
/*Special symbols.*/
#define SymbolBlank '.' /*Symbol that denotes a blank square.*/
#define SymbolFixed '$' /*Symbol that cannot move.*/
/*Board dimensiona.*/
#define BoardHeight 3
#define BoardWidth 4
#define BoardSize 12
/*Start position.*/
/* N I T E */
/* $ . $ . */
/* D A Y . */
#define StartBoard "NITE$.$.DAY."
/*Goal position.*/
/* D A Y . */
/* $ . $ . */
/* N I T E */
#define GoalBoard "DAY.$.$.NITE"
/*Number of moves in a minimal length solution for this puzzle,*/
/* where one move is defined as s moving a piece vertically or horizontally*/
/* to an adjacent unoccupied square (and the SymbolFixed piece cannot move).*/
#define MinSolution 66
/*Data structure parameters.*/
#define QueueArraySize 50000 /*Queue goes from 0 to QueueArraySize-1.*/
#define HashArraySize 1000003 /*Hash table goes from 0 to HashArraySize-1.*/
#define HashStatsMAX 50 /*Max number of hash bucket size statistics to keep.*/
Output.h
/*Output a position; takes 4 arguments:
*POS: String that lists pieces in row major order.
step: The step number (ignore next two args when step=0).
piece: Piece that moved.
dir: Direction that the piece moved; 0=north, 1=east, 2=south, 3=west.
*/
void OutputPosition(char *POS, int step, char piece, int dir) {
static char *DirectionString[4] = {"north", "east", "south", "west"};
int i;
printf("\nStep %d",step);
if (step>0) printf(", move %c %s",p