MLE求调

P1443 马的遍历

VillagerFriend @ 2024-10-24 21:08:39

只过了第一,第二和最后一个点,其他全部MLE


#include <bits/stdc++.h>
using namespace std;

const int MAXX = 500;
int dx[8] = {-1,-2,-2,-1,1,2,2,1};
int dy[8] = {-2,-1,1,2,2,1,-1,-2};
queue <pair<int,int>> qx;
int n,m,x,y;
int a[MAXX][MAXX];
bool b[MAXX][MAXX];

int main()
{
    scanf("%d%d%d%d",&n,&m,&x,&y);

    qx.push({x,y});
    a[x][y] = 1;
    b[x][y] = true;
    while(!qx.empty())
    {
        int tx=qx.front().first;
        int ty=qx.front().second;
        b[tx][ty] = 1;
        qx.pop();
        for(int i = 0;i < 8;i++)
        {
            int xx = tx + dx[i];
            int yy = ty + dy[i];
            if(xx<1 || xx>n || yy<1 || yy>m){continue;}
            if(!b[xx][yy])
            {
                a[xx][yy]=a[tx][ty]+1;
                qx.push({xx,yy});
            }
        }
    }

    for(int i = 1;i <= n;i++)
    {
        for(int j = 1;j <= m;j++)
        {
            printf("%d ",a[i][j]-1);
        }
        puts("");
    }
    return 0;
}```

by Lmh1128 @ 2024-10-24 21:17:20

入队时打标记,不然一个队列一堆相同的数


by Metro_Line5 @ 2024-10-24 21:18:21

@VillagerFriend 广搜没去重。。。乐子


by Lmh1128 @ 2024-10-24 21:18:39

#include <bits/stdc++.h>
using namespace std;

const int MAXX = 500;
int dx[8] = {-1,-2,-2,-1,1,2,2,1};
int dy[8] = {-2,-1,1,2,2,1,-1,-2};
queue <pair<int,int>> qx;
int n,m,x,y;
int a[MAXX][MAXX];
bool b[MAXX][MAXX];

int main()
{
    scanf("%d%d%d%d",&n,&m,&x,&y);

    qx.push({x,y});
    a[x][y] = 1;
    b[x][y] = true;
    while(!qx.empty())
    {
        int tx=qx.front().first;
        int ty=qx.front().second;
        b[tx][ty] = 1;
        qx.pop();
        for(int i = 0;i < 8;i++)
        {
            int xx = tx + dx[i];
            int yy = ty + dy[i];
            if(xx<1 || xx>n || yy<1 || yy>m){continue;}
            if(!b[xx][yy])
            {
                a[xx][yy]=a[tx][ty]+1;
                qx.push({xx,yy});
                /*唯一改动*/b[xx][yy] = 1;
            }
        }
    }

    for(int i = 1;i <= n;i++)
    {
        for(int j = 1;j <= m;j++)
        {
            printf("%d ",a[i][j]-1);
        }
        puts("");
    }
    return 0;
}

by Lmh1128 @ 2024-10-24 21:19:04

@VillagerFriend


by VillagerFriend @ 2024-10-24 22:31:29

@Lmh1128 谢谢


|