我执行BFS期间出现运行时错误

时间:2014-01-17 19:07:45

标签: c++ algorithm runtime-error

我编写了一个在图表中执行BFS的代码。但是在我给出第二个输入之后它崩溃了。问题是什么。我试图解决它,但它导致程序更加有效地工作。

#include<iostream>
#include<vector>
#include<algorithm>
#include<deque>




using namespace std;
enum color{
    white, gray, black
};

static const int nil=-2147483645;
class graph{
    public:
        int key;
        int parent;
        int dis;
        color col;

};
vector<vector<graph> > g;

int BFS(graph source, graph target){
        deque<graph> Q;
        Q.push_back(source);

    while(!Q.empty()){
            graph current=*Q.begin();
            Q.pop_front();
                if(current.key == target.key){
                return current.dis;
            }
            current.col=gray;

        for(vector<graph>::iterator m=(g[current.key-1]).begin();m!=(g[current.key-1]).end();m++){
            if ( (current.parent) != (m->key) ){
                    m->parent=current.key;
                    m->col=gray;
                    m->dis=current.dis+1;
                    Q.push_back(*m);
            }
        } 
    }
    return 0;
}

int main(){
        int no_vertex;cin>>no_vertex;
        int no_edge;cin>>no_edge;
//where I think the error occurs
        for(int cnt=0;cnt!=no_edge;cnt++){
            graph temp1,temp2;
            cin>>temp1.key>>temp2.key;
            temp1.col=white;
                temp2.col=white;
            temp1.dis=0;
            temp2.dis=0;
            temp1.parent=nil;
            temp2.parent=nil;

            (g[temp1.key-1]).push_back(temp2);
             (g[temp2.key-1]).push_back(temp1);
        }
//^ error is probably between the two comments
            graph (source,target);
            cin>>source.key>>target.key;
                    source.col=white;
                target.col=white;
            source.dis=0;
            target.dis=0;
            source.parent=nil;
            target.parent=nil;

 }

在给出第二个(图的第一对顶点)输入之后...... Windows说该程序已停止工作。请点击here查看问题和示例输入

输入的第一行包含两个整数N和M. N是建筑物的数量:我们假设我们的建筑物编号为1,2,...,N。 M是导演列出的足够接近从一个跳到另一个的建筑物对的数量。接下来的M行中的每一行,即行2,...,M + 1,包含一对整数,表示一对靠近的建筑物。线i + 1包含整数Ai和Bi,1≤Ai≤N且1≤Bi≤N,表明建筑物Ai和Bi足够接近。最后一行,第M + 2行包含一对整数S和T,其中S是Hero开始搜索的建筑物,而T是建筑物所在的建筑物。

示例输入

5 5

1 3

示例输入1:

5 5

1 3

2 3

1 2

3 5

4 5

1 4

示例输出1:

3

示例输入2:

5 3

1 3

1 2

4 5

1 4

示例输出2:

0

1 个答案:

答案 0 :(得分:2)

在你的代码中,g被声明为向量的向量。最初它包含0个图形向量。

vector<vector<graph> > g;

您应该向其添加元素。通过使用push_back或.resize()和顶点数。

int main(){
        int no_vertex;cin>>no_vertex;
        int no_edge;cin>>no_edge;
        g.resize(no_vertex);
        ^^^^^^^^^^^^^^^^^^^ //fix
        ...

这是您的代码中断的地方:

(g[temp1.key-1]).push_back(temp2);
 ^^^^^^^^^^^^^^
(g[temp2.key-1]).push_back(temp1);
 ^^^^^^^^^^^^^^

如果您使用.at,您将获得例外。例如:

 g.at(temp1.key-1).push_back(temp2);

更好的方法是使用“包和邻接列表”std::unordered_map<>(C ++ 11),如果您没有支持C ++ 11的编译器而使用std::map<>

std::unordered_map<graph, vector<graph>>