骑士巡游问题

 /*
 ============================================================================
 Name        : Exercise.c
 Author      : Haier
 Version     : 1.01
 Copyright   : Copyright (c) 2014
 Description : Knight Parade in C, Ansi-style,Compile by Code:Block
 ============================================================================
 */
#include <stdio.h>
#define Order (5)

int Matrix[Order][Order];
int a[8]= {2,1,-1,-2,-2,-1,1,2};  /*(a[],b[])组对,控制方向*/
int b[8]= {1,2,2,1,-1,-2,-2,-1};

/****************************************************************************
* Function     : Print
* Description  : Print result
* Input        : void
* Return       : void
*****************************************************************************/
void Print()
{
    int i,j;

    for(i=0; i<Order; i++)
    {
        for(j=0; j<Order; j++)
        {
            printf("%4d",Matrix[i][j]);
        }

        printf("\n");
    }

    printf("\n");
}
/****************************************************************************
* Function     : Try
* Description  : Recursive lookup the correct position
* Input        : times of recursive,position of x,position of y
* Return       : void
*****************************************************************************/
void Try(int times,int PosOfx,int PosOfy)
{
    int NextPosOfx,NextPosOfy,i;

    for(i=0; i<8; i++)
    {
        NextPosOfx=PosOfx+a[i];
        NextPosOfy=PosOfy+b[i];

        if(NextPosOfx>=0 && NextPosOfx<Order && NextPosOfy>=0 && NextPosOfy<Order)
        {
            if(Matrix[NextPosOfx][NextPosOfy]==0)
            {
                Matrix[NextPosOfx][NextPosOfy]=times;

                if(times<Order*Order)
                {
                    Try(times+1,NextPosOfx,NextPosOfy);
                }
                else
                {
                    Print();
                }
                Matrix[NextPosOfx][NextPosOfy]=0;
            }

        }
    }
}

int main()
{
    int x,y;

    printf("Please input the position of knight: ");
    scanf("%d,%d",&x,&y;

    Matrix[x][y]=1;
    Try(2,x,y);
}
    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/u011640816/article/details/24937155
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞