马踏棋盘算法

来源:互联网 发布:爱知日语培训班多少钱 编辑:程序博客网 时间:2024/04/30 20:40

马踏棋盘问题(又称骑士周游或骑士漫游问题)是算法设计的经典问题之一
这里写图片描述
算法牵涉 深度优先搜索与回溯法
回溯法:一条路走到天黑,碰壁后退回上一步改变一次方向,如果还是碰壁或者下一格已经走过那么再次退回上一步。
这里写图片描述

源代码如下:

#include<stdio.h>#include<time.h>

define X 8

define Y 8

int chess[X][Y];  //定义棋盘 void print(){    int i,j;    for(i = 0;i < X; i++)    {        for(j = 0;j< Y;j++)        {            printf("%5d",chess[i][j]);        }        printf("\n");    }    printf("\n"); } int nextxy(int *x,int *y,int count){    //八种走的方法     switch(count)    {        case 0:            if(*x + 2 <= X-1&&*y-1 >= 0&&chess[*x+2][*y-1] ==0)            {                *x +=2;                *y -=1;                return 1;            } break;        case 1:            if(*x + 2 <= X - 1&&*y + 1 <= Y-1&&chess[*x+2][*y+1] ==0)            {                *x +=2;                *y +=1;                return 1;            } break;        case 2:            if(*x + 1 <= X - 1&&*y - 2 >= 0&&chess[*x+1][*y-2] ==0)            {                *x +=1;                *y -=2;                return 1;            } break;        case 3:            if(*x - 1 >= 0&&*y - 2 >= 0&&chess[*x-1][*y-2] ==0)            {                *x -=1;                *y -=2;                return 1;            } break;        case 4:            if(*x - 2 >= 0&&*y - 1 >= 0&&chess[*x-2][*y-1] ==0)            {                *x -=2;                *y -=1;                return 1;            } break;        case 5:            if(*x - 2 >= 0&&*y + 1 <= Y-1&&chess[*x-2][*y+1] ==0)            {                *x -=2;                *y +=1;                return 1;            } break;        case 6:            if(*x - 1 >= 0&&*y + 2 <= Y-1&&chess[*x-1][*y+2] ==0)            {                *x -=1;                *y +=2;                return 1;            } break;        case 7:            if(*x + 1 <= X - 1&&*y + 2 <= Y-1&&chess[*x+1][*y+2] ==0)            {                *x +=1;                *y +=2;                return 1;            } break;        default :            break;    }    return 0; } //深度优先遍历棋盘 x,y为位置 tag为标记变量 每走一步加1 int TravelChessBoard(int x,int y,int tag) {    int x1 = x,y1 = y,count = 0, flag=0;    chess[x][y] = tag;    if(X*Y ==tag)    {        //打印棋盘         print();        return 1;     }    flag = nextxy(&x1,&y1,count);   //找到马的下一坐标位置x1,y1 找到flag = 1,找不到flag = 0.     while (flag ==0&&count <7)    {        count++;        flag = nextxy(&x1,&y1,count);    }    while(flag)    {        if(TravelChessBoard(x1,y1,tag+1))//递归查找         {            return 1;        }    //如果条件不满足就回溯          x1 = x;        y1 = y;        count ++;        flag = nextxy(&x1,&y1,count);     }    if(!flag)//再不满足就再次回溯且把当前位置归0      {        chess[x][y] = 0;     }      return 0;  }   int main()  {    int i ,j;    for(i = 0;i < X; i++)    {        for(j = 0;j<Y;j++)        {            chess[i][j] = 0;        }    }    if(!TravelChessBoard(2,0,1))    {        printf("fail \n");    }    return 0;  }

这里写图片描述

0 0
原创粉丝点击