马走日 全手打

因为天梯赛不能看板子,我的板子上有马走日这题

我误以为是dfs

实际上是bfs

说明两点:我的基础不牢固、我的搜索是真的很薄弱

但是,失败了,得从原地爬起来,加油,逆风中前行的人!

有一个 n \times mn×m 的棋盘,在某个点 (x, y)(x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。

输入格式

输入只有一行四个整数,分别为 n, m, x, yn,m,x,y。

输出格式

一个 n \times mn×m 的矩阵,代表马到达某个点最少要走几步(左对齐,宽 55 格,不能到达则输出 -1−1)。

输入输出样例

输入 #1复制

3 3 1 1

输出 #1复制

0    3    2    
3    -1   1    
2    1    4    

说明/提示

数据规模与约定

对于全部的测试点,保证 1 \leq x \leq n \leq 4001≤x≤n≤400,1 \leq y \leq m \leq 4001≤y≤m≤400。

#include<bits/stdc++.h>
using namespace std;
#define PII pair<int,int>
queue<PII>q;
int n,m,x,y;
const int maxn=405;
int f[maxn][maxn];
bool vis[maxn][maxn];
int dx[8]= {2,2,1,1,-1,-1,-2,-2};
int dy[8]= {1,-1,2,-2,2,-2,1,-1};
void bfs(int x,int y)
{
    memset(f,-1,sizeof(f));
    vis[x][y]=1;
    f[x][y]=0;
    q.push(make_pair(x,y));
    while(!q.empty())
    {
        int xx=q.front().first;
        int yy=q.front().second;
        q.pop();
        for(int i=0;i<8;i++)
        {
            int sx=xx+dx[i];
            int sy=yy+dy[i];
            if(sx>=1&&sy>=1&&sx<=n&&sy<=m&&vis[sx][sy]==0)
            {
                vis[sx][sy]=1;
                f[sx][sy]=f[xx][yy]+1;
                q.push(make_pair(sx,sy));
            }
        }

    }
}
int main()
{
    cin>>n>>m>>x>>y;
    bfs(x,y);
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            printf("%-5d",f[i][j]);
        }
        cout<<endl;
    }







    return 0;
}

天梯赛代码,由于无法检测,90%以上是对的

#include<bits/stdc++.h>
using namespace std;
#define PII pair<int,int>
queue<PII>q;
int n,x,y;
const int maxn=1005;
int f[maxn][maxn];
bool vis[maxn][maxn];
int dx[8]= {2,2,1,1,-1,-1,-2,-2};
int dy[8]= {1,-1,2,-2,2,-2,1,-1};
void bfs(int x,int y)
{
    memset(f,-1,sizeof(f));
    vis[x][y]=1;
    f[x][y]=0;
    q.push(make_pair(x,y));
    while(!q.empty())
    {
        int xx=q.front().first;
        int yy=q.front().second;
        q.pop();
        for(int i=0;i<8;i++)
        {
            int sx=xx+dx[i];
            int sy=yy+dy[i];
            if(sx>=1&&sy>=1&&sx<=n&&sy<=n&&vis[sx][sy]==0)
            {
                vis[sx][sy]=1;
                f[sx][sy]=f[xx][yy]+1;
                q.push(make_pair(sx,sy));
            }
        }

    }
}
int main()
{
    cin>>n>>x>>y;
    bfs(x,y);
     cout<<f[1][1]<<endl;
     cout<<f[1][n]<<endl;
     cout<<f[n][1]<<endl;
     cout<<f[n][n]<<endl;







    return 0;
}

数据

20
1 1


0
11
11
14

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值