基于广度优先搜索的拼图游戏算法

本文介绍了如何运用广度优先搜索(BFS)算法来解决经典的八数码问题。通过将起始状态存入哈希表并逐步遍历所有可能的移动,直到找到目标状态。在实现过程中,记录了队列和哈希表的状态,展示了解决问题的具体步骤及效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值