zoj 1091 Knight Moves

  题目见zoj 1091

  使用宽度搜索优先来求解,这个算法已经忘记的差不多了,所以写出来的代码很罗嗦,看起来很不清晰。

  好像还可以直接用公式或者神经网络算法求解,详见Knight's Tour

 

/* zoj 1091 Knight Moves */
#include <stdio.h>
#include <string.h>
#define MAX 100
#define BOARDSIZE (8+1)
struct queueStruct{
  int x;
  int y;
  int step;
}queue[MAX],tempQueue;
int front;
int  rear;
int minStep;
int isVisited[BOARDSIZE][BOARDSIZE];
const int searchTable[8][2] = {{-2,-1},{-1,-2},{-2,1},{-1,2},{1,2},{2,1},{1,-2},{2,-1}};
int bfs(int startx, int starty, int endx, int endy, int step);

int main(void)
{
  char src[3],des[3];
  int startx, starty, endx, endy;
  while(scanf("%s %s",src,des) == 2)
    {
      memset(isVisited,0,sizeof(isVisited));
      memset(queue,0,sizeof(queue));
      front = rear = 0;
      startx = src[0] - 'a' + 1;
      starty = src[1] - '0';
      endx = des[0] - 'a' + 1;
      endy = des[1] - '0';
      bfs(startx,starty,endx,endy,0);
      printf("To get from %s to %s takes %d knight moves.\n",src,des,minStep);
    }
  return 0;
}
int bfs(int startx, int starty, int endx, int endy, int step)
{
  int i;
  struct queueStruct q;
  if(startx == endx && starty == endy)
    {
      minStep = step;
      return 0;
    }
  isVisited[startx][starty] = 1;
  tempQueue.x = startx;
  tempQueue.y = starty;
  tempQueue.step = step;
  queue[rear++] = tempQueue;
  while(front < rear)
    {
      tempQueue = queue[front++];
      for(i = 0; i < BOARDSIZE; i++)
	{
	  /*	  q = tempQueue;*/
	  q.x = tempQueue.x + searchTable[i][0];
	  q.y = tempQueue.y + searchTable[i][1];
	  q.step = tempQueue.step + 1;
	  if(q.x < 1 || q.x > 8 || q.y < 1 || q.y > 8 ||isVisited[q.x][q.y])
	    continue;
	  if(q.x == endx && q.y == endy)
	    {
	      minStep = q.step;
	      return 0;
	    }
	  queue[rear++] = q;
	  isVisited[q.x][q.y] = 1;
	}
    }
  return 0;
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值