bad_alloc错误进入内置队列。是什么原因?

时间:2017-04-01 13:54:48

标签: c++ data-structures

bad_alloc错误来了。是什么原因? 代码试图找到从给定起点到目标点的路径,而不是在X上移动并且仅在水平和垂直方向上移动。在网格上名为Castle的数据结构 - >队列下的hackerrank上存在问题。

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;


int main() {
    int N;
    cin>>N;
    string s[N];
    for(int i=0;i<N;i++)
        cin>>s[i];
    int a,b,c,d;
    cin>>a>>b>>c>>d;
    queue<int> x,y,dist,h;
    int v[N][N];
    for(int i=0;i<N;i++){
        for(int j=0;j<N;j++)
            v[i][j]=0;
    }
    v[a][b]=1;
    if(b-1>=0 && s[a][b-1]!='X'){
        x.push(a);
        y.push(b-1);
        h.push(1);
        dist.push(1);
    }
    if(b+1<N && s[a][b+1]!='X'){
        x.push(a);
        y.push(b+1);
        h.push(1);
        dist.push(1);
    }
    if(a-1>=0 && s[a-1][b]!='X'){
        x.push(a-1);
        y.push(b);
        h.push(0);
        dist.push(1);
    }
    if(a+1<N && s[a+1][b]!='X'){
        x.push(a+1);
        y.push(b);
        h.push(0);
        dist.push(1);
    }
    int minSteps=1000000000;
    while(!x.empty()){
        int cx=x.front();
        int cy=y.front();
        int h1=h.front();
        int d1=dist.front();
        v[cx][cy]=1;
        x.pop();y.pop();
        h.pop();dist.pop();
        if(cx==c && cy==d){
            if(d1<minSteps)
                minSteps=d1;
        }
        else{
            if(cy-1>=0 && v[cx][cy-1]==0 && s[cx][cy-1]!='X'){
                x.push(cx);
                y.push(cy-1);
                if(h1==0)
                    dist.push(d1+1);
                else
                    dist.push(d1);
                h.push(1);
            }
            if(cy+1<N && v[cx][cy+1]==0 && s[cx][cy+1]!='X'){
                x.push(cx);
                y.push(cy+1);
                if(h1==0)
                    dist.push(d1+1);
                else
                    dist.push(d1);
                h.push(1);
            }
            if(cx-1>=0 && v[cx-1][cy]==0 && s[cx-1][cy]!='X'){
                x.push(cx-1);
                y.push(cy);
                if(h1==1)
                    dist.push(d1+1);
                else
                    dist.push(d1);
                h.push(0);
            }
            if(cx+1<N && v[cx+1][cy]==0 && s[cx+1][cy]!='X'){
                x.push(cx+1);
                y.push(cy);
                if(h1==1)
                    dist.push(d1+1);
                else
                    dist.push(d1);
                h.push(0);
            }
        }
    }
    cout<<minSteps<<endl;
    return 0;
}

0 个答案:

没有答案