1330:【例8.3】最少步数

这是一道广搜题,主要难在于方向数组一个是马,一个是象,如果这个方向数组记不下来的话在纸上画一画就知道了不然只能背了

AC:

#include <bits/stdc++.h>
using namespace std;
int n,m;
bool vis[105][105];
int t[12][2]={{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-2},{-2,2},{2,2},{2,-2}}; 
struct node{
    int x,y,step;
};
int bfs(int x,int y){
    node now,pos,next;
    now.x=x, now.y=y, now.step=0;
    queue<node> q;
    q.push(now);
     while(!q.empty()){
        pos = q.front();
         q.pop();
        if(pos.x == 1 && pos.y == 1) return pos.step;
         for(int i=0; i<12; i++){
            int bx = pos.x+t[i][0], by = pos.y+t[i][1];
            if(bx < 0 || bx > 100 || by < 0 || by > 100) continue; 
            if(vis[bx][by]==1) continue;
            vis[bx][by]=1;
            next.x=bx; next.y=by; next.step=pos.step+1; ;
            q.push(next);
        }
    }
}
int main(){
    while(cin >> n >> m){
        memset(vis,0,sizeof(vis));
        vis[n][m]=1;
        cout << bfs(n,m) << endl;
    }
    return 0;
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值