• 马踏棋盘(非递归)


    #include <iostream.h>


    struct point
    {
    int x,y;//马的位置
    int dir;//这一次马行走的方向
    };


    struct stack
    {
    point p[64];//存储马的位置,方便回溯
    };
    int board [8][8];
    int Htry1[8]={-2,-1,1,2,2,1,-1,-2};
    int Htry2[8]={1,2,2,1,-1,-2,-2,-1};
    bool chech[8][8]={0};//标记位置是否已经被占用
    int main()
    {
    int i,j;
    int top=0;
    int z;
    cout<<"请输入马的初始位置";
    cin>>i;
    cin>>j;
    stack sta;
    sta.p[top].x=i;
    sta.p[top].y=j;
    board [i][j]=top;
    chech [i][j]=true;
    int nx;
    int ny;


    for(int u=0;u<64;u++)
    sta.p[u].dir=0;//把每个结点的dir清零
    for(z=0;;)
    {

    if(sta.p[top].x+Htry1[z]>=0&&sta.p[top].x+Htry1[z]<8&&
    sta.p[top].y+Htry2[z]>=0&&sta.p[top].y+Htry2[z]<8&&
    !chech [sta.p[top].x+Htry1[z]][sta.p[top].y+Htry2[z]]//检查要走的下个位置是否可行
    )
    {
    nx=sta.p[top].x+Htry1[z];
    ny=sta.p[top].y+Htry2[z];
    sta.p[top].dir=z;
    top++;
    sta.p[top].x=nx;
    sta.p[top].y=ny;
    board [nx][ny]=top;
    chech [nx][ny]=true;
    z=-1;
    }
    else if(z==7)//如果不可行,而且是最好一次检查
    { chech [sta.p[top].x][sta.p[top].y]=false;
    top--;
    while(1)
    {
    z=sta.p[top].dir;
    if(z!=7)
    break;
    else
    { chech [sta.p[top].x][sta.p[top].y]=false;
    top--;
    }
    }
    }
    if(top==-1||top==63)break;//如果回溯到-1,或者栈满,则退出循环
    z++;


    }
    for(i=0;i<8;i++)
    {
    for(j=0;j<8;j++)
    cout<<board [i][j]<<"";
    cout<<endl;
    }
    return 1;
    }
  • 相关阅读:
    github使用
    部署flask
    docker部署路飞学城
    centos7安装dnsmasq局域网dns
    消息队列rabbitmq
    记录腾讯云中矿机病毒处理过程(重装系统了fu*k)
    Golang基础
    git协同开发
    gitlab与pycharm结合
    github与gitlab与git三个基佬的故事
  • 原文地址:https://www.cnblogs.com/wonderKK/p/2240364.html
Copyright © 2020-2023  润新知