空间炸了,全是MLE,求助!!!

P1746 离开中山路

Tune_ @ 2020-01-16 17:26:16

代码奉上:

#include<bits/stdc++.h>
using namespace std;
struct data
{
    int x,y,s;
}kk;
queue<data> q;
int n,sx,sy,fx,fy;
int dx[5]={0,1,-1,0,0};
int dy[5]={0,0,0,1,-1};
char a[1001][1001];
void bfs(int nx,int ny)
{
    kk.x=nx;kk.y=ny;kk.s=0;
    q.push(kk);
    while(!q.empty())
    {
        kk=q.front();
        q.pop();
        for(int i=1;i<=4;i++)
        {
            int xx=kk.x+dx[i],yy=kk.y+dy[i];
            if(xx>=1&&xx<=n&&yy>=1&&yy<=n&&a[xx][yy]=='0')
            {
                if(xx==fx&&yy==fy)
                {
                    cout<<kk.s+1;
                    return;
                }
                else
                {
                    data k;
                    k.x=xx;
                    k.y=yy;
                    k.s=kk.s+1;
                    q.push(k);
                }
            }
        }
    }
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    for(int j=1;j<=n;j++)cin>>a[i][j];
    cin>>sx>>sy>>fx>>fy;
    bfs(sx,sy);
    return 0;
}

请各位大佬指点!!!


by _yjh @ 2020-01-16 17:30:03

#include<iostream>
#include<queue>
using namespace std;
struct Pos
{
    int x,y;
};
queue <Pos> q;
int n,x,y,tx,ty,dis[1001][1001],s_a,s_b,t_a,t_b;
const int dx[]={1,-1,0,0};
const int dy[]={0,0,1,-1};
char mp[1001][1001];
bool vis[1001][1001];
int bfs(int sx,int sy)
{
    q.push((Pos){sx,sy});
    vis[sx][sy]=true;
    while(!q.empty())
    {
        x=q.front().x;
        y=q.front().y;
        q.pop();
        if(x==t_a&&y==t_b) return dis[x][y];
        for(int i=0;i<4;i++)
        {
            tx=x+dx[i];
            ty=y+dy[i];
            if(tx<=0||tx>n||ty<=0||ty>n) continue;
            if(mp[tx][ty]=='1'||vis[tx][ty]==true) continue;
            dis[tx][ty]=dis[x][y]+1;
            vis[tx][ty]=true;
            q.push((Pos){tx,ty});
        }
    }
    return -1;
}
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            cin>>mp[i][j];
    cin>>s_a>>s_b>>t_a>>t_b;
    cout<<bfs(s_a,s_b);
    return 0;

}

by _yjh @ 2020-01-16 17:30:18

@lucy2008 我的代码


by zfz04 @ 2020-01-16 17:34:37

没有加vis标记,


by goodkillerchen @ 2020-04-21 14:21:25

我也爆空间


|