马踏棋盘

在一个8*8的棋盘中,输入棋盘位置,马遍历棋盘中每一个格子;
要求输出马所踏出的每一步在棋盘的位置。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 8
#define MAXSIZE 64
typedef struct
{
    int x, y;
}node;
typedef struct
{
    node list[MAXSIZE];
    int top;
}SeqStack;
void InitStack(SeqStack *s)
{
    s->top = -1;
}
int Push(SeqStack *s, node n)
{
    if (s->top == MAXSIZE-1)
        return 0;
    else
    {
        s->top++;
        s->list[s->top] = n;
        return 1;
    }
}
int Pop(SeqStack *s)
{
    if (s->top == -1)
        return 0;
    else
    {
        s->top--;
        return 1;
    }
}
int IsEmpty(SeqStack *s)
{
    if (s->top == -1)
        return 1;
    return 0;
}
node  GetTop(SeqStack *s)       //此函数并不严谨
{
        node x;
        x = s->list[s->top];
        return x;
}
int map[N][N], book[N][N]; //map为输出位置数组, book为标记数组
int next[8][2] = {-2, 1, -1, 2, 1, 2, 2, 1, 2, -1, 1, -2, -1, -2, -2, -1};
int flag = 0;
SeqStack s;
void Dfs(int x, int y, int step)
{
    //SeqStack s;

    if(step == 64)
    {
        flag = 1;
        int count = 0;
        while (!IsEmpty(&s))
        {
            node n = GetTop(&s);
            Pop(&s);
            map[n.x][n.y] = 64-(count++);
        }
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                printf("%2d ", map[i][j]);
            }
            printf("\n");
        }
        return;
    }
    for (int i = 0; i < N; i++)
    {
        int x1 = x+next[i][0];
        int y1 = y+next[i][1];
        //跳过非法位置
        if (x1 < 0 || y1 < 0 || x1 > N-1 || y1 > N-1 || book[x1][y1] == 1)
        {
            continue;
        }
        if(book[x1][y1] == 0)
        {
            book[x1][y1] = 1;
            node p;
            p.x = x1;
            p.y = y1;
            Push(&s, p);
            Dfs(x1, y1, step+1);
            if (flag) return;
            book[x1][y1] = 0;
            Pop(&s);
        }
    }
    return;
}
int main(void)
{
    InitStack(&s);
    memset(book, 0, sizeof(book));
    int x, y;
    scanf("%d%d", &x, &y);
    map[x-1][y-1] = 1;
    book[x-1][y-1] = 1;
    Dfs(x-1, y-1, 1);
    return 0;
}
程序输出样例
1 1
1 38 55 34  3 36 19 22
54 47  2 37 20 23  4 17
39 56 33 46 35 18 21 10
48 53 40 57 24 11 16  5
59 32 45 52 41 26  9 12
44 49 58 25 62 15  6 27
31 60 51 42 29  8 13 64
50 43 30 61 14 63 28  7
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值