如何在C ++中编写广度优先搜索的代码

时间:2016-03-31 07:15:14

标签: c++ breadth-first-search

我一直在尝试从Hackerrank对问题进行图表搜索。最后,我想出了

#include <cstdio>
#include <list>
using namespace std;

void bfs(list<int> adjacencyList[], int start, int countVertices) {
    // initialize distance[]
    int distance[countVertices];
    for(int i=0;i < countVertices; i++) {
        distance[i] = -1;
    }

    list<int>::iterator itr;
    int lev = 0;
    distance[start-1] = lev;          // distance for the start vertex is 0
                                      // using start -1 since distance is array which are 0-indexed

    list<int> VertexQueue;
    VertexQueue.push_back(start);

    while(!VertexQueue.empty()) {
        int neighbour = VertexQueue.front();
        itr = adjacencyList[neighbour].begin();

        while(itr != adjacencyList[neighbour].end()) {
            int vertexInd = (*itr) - 1;
            if(distance[vertexInd] == -1) {           // a distance of -1 implies that the vertex is unexplored
                distance[vertexInd] = (lev + 1) * 6;
                VertexQueue.push_back(*itr);
            }
            itr++;
        }
        VertexQueue.pop_front();
        lev++;
    }

    // print the result
    for(int k=0;k< countVertices;k++) {
        if (k==start-1) continue;     // skip the start node
        printf("%d ",distance[k]);
    }
}

int main() {
    int countVertices,countEdges,start,T,v1,v2;

    scanf("%d", &T);

    for(int i=0; i<T; i++) {
        scanf("%d%d", &countVertices,&countEdges);

        list<int> adjacencyList[countVertices];

        // input edges in graph
        for(int j=0; j<countEdges; j++) {
            scanf("%d%d",&v1,&v2);
            adjacencyList[v1].push_back(v2);
            adjacencyList[v2].push_back(v1);        // since the graph is undirected
        }

        scanf("%d",&start);

        bfs(adjacencyList, start, countVertices);
        printf("\n");
    }

    return 0;
}

然而,这导致了“分段错误”,我无法弄清楚我的错误。 此外,我经常遇到分段错误,但不知道如何调试它。如果有人能让我对此有所了解,那就太好了。

1 个答案:

答案 0 :(得分:0)

scanf("%d%d", &countVertices,&countEdges);
list<int> adjacencyList[countVertices];

以上代码显示错误。如果您的索引以1开头,请将adjacencyList大小设为countVertices + 1或减少uv,然后再将其放入列表中。

您还可以使用(无序)地图映射顶点到不会发生段错误的列表。

同样不是VLA不是标准C ++的一部分,所以即使你的编译器支持它们作为扩展,也要避免使用它们。