深度优先搜索DFS

题目:一个棋盘格9*10,按照象棋马走“日”的规则,从起点走到终点,且走过的路不能重新走,设计一个算法实现!

分析:
本题是典型的深度优先搜索的题目,首先分析马在一个位置时所能走的下一个位置时的走法,共有8种。如下图所示马所在位置所能到达的地方:
这里写图片描述
移动规则为:

int dx[] = {2,1,-1,-2,-2,-1,1,2};
int dy[] = {1,2,2,1,-1,-2,-2,-1};

每次所能移动的位置的变量约束关系如上。具体如下代码所示:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<queue>

using namespace std;
struct horse{   //定义一个马
    int sx,sy;
    int iSetp;
};
bool visit[9][10]={0};  //定义 9*10大小的棋盘格

int dx[] = {2,1,-1,-2,-2,-1,1,2};
int dy[] = {1,2,2,1,-1,-2,-2,-1};

bool Horse(int sx,int sy,int ex,int ey)  // 主要程序
{
    horse hor;

    if(sx<0 || sx>8 || sy<0 || sy>9 || ex<0 || ex>8 || ey<0 ||ey>9)
    {
        cout<<"Error!"<<endl;
        return false;
    }
    hor.sx = sx;
    hor.sy = sy;
    queue<horse> d;
    d.push(hor);
    if(hor.sx == ex && hor.sy == ey)
        return true;
    visit[sx][sy] = true;
    while(hor.sx != ex || hor.sy != ey)
    {
        for(int i = 0 ; i < 8;i++)
        {
            hor = d.front();
            //horse temp1;
            cout<<"front:"<<hor.sx<<"::"<<hor.sy<<endl;
            hor.sx += dx[i];
            hor.sy += dy[i];
            if(hor.sx < 0 || hor.sx >=9 || hor.sy < 0 || hor.sy >=10)
                continue;
            if(9>hor.sx>=0 && 10>hor.sy>=0)
                {
                    if(visit[hor.sx][hor.sy] != true)
                      {
                         d.push(hor);
                         cout<<"d :"<<hor.sx<<"::"<<hor.sy<<endl;
                         if(hor.sx == ex && hor.sy == ey)
                            return true;
                         visit[hor.sx][hor.sy] = true;
                      }
                }               
        }
        d.pop();
        if(d.empty())
        {
            return false;
        }
        hor = d.front();    
    }
}
int main(int argc,char** argv)
{
    bool temp = Horse(8,9,8,8);
    cout<<"result = "<<temp<<endl;
    system("pause");
    return 0;
}

Output:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值