无初始化的变量返回分段错误

时间:2015-06-12 01:03:22

标签: c++ graph segmentation-fault

描述:     你的一个朋友正在研究旅行骑士问题(TKP),在那里你可以找到最短的骑士动作闭路游览,它只能在棋盘上的一组给定的n个方格的每个方格上访问一次。他认为问题最困难的部分是确定两个给定方格之间骑士移动的最小数量,一旦你完成了这个,找到巡回赛就很容易了。当然你知道反之亦然。所以你让他写一个解决“困难”部分的程序。你的工作是编写一个程序,它将两个方格a和b作为输入,然后确定从a到b的最短路径上的骑士移动次数。

有多个测试用例。第一行包含整数T,表示测试用例的数量。每个测试用例由一行包含两个由一个空格分隔的正方形组成。正方形是由表示列的字母(a-h)和表示棋盘上的行的数字(1-8)组成的字符串。

对于每个测试用例,打印一行说“从xx到yy需要n个骑士移动。”。     * /

class Graph{
    int V;
    list<int> *adj;
public:
    //constructor, use adjacent list to represent the graph        
Graph(int V){
    V = V;
    adjacent = new list<int>[V];
}
void add(int i,int j){
    adjacent[i].push_back(j);
    adjacent[j].push_back(i);
}
// build the chess board
void add(int i){
    if(i + 1 >= 0 && i + 1 <= 63 && ((i + 1) / 8 == i / 8))                              
        add(i,i + 1);
    if(i + 7 >= 0 && i + 7 <= 63 && ((i + 7) / 8 == i / 8 + 1))
        add(i,i + 7);
    if(i + 8 >= 0 && i + 8 <= 63 && ((i + 8) / 8 == i / 8 + 1))
        add(i,i + 8);
    if(i + 9 >= 0 && i + 9 <= 63 && ((i + 9) / 8 == i / 8 + 1))
        add(i,i + 9);
}
//use BFS to find the shortest path from s to e
int BFS(int s ,int e){
    vector<bool> visited ;
    for(int i = 0; i < V; i++)
        visited.push_back(false);
    vector<int> distances;
    for(int i = 0; i < V; i++)
        distances.push_back(-1);
    distances[s] = 0;
    for(int current = 0; current < V; current++){
        for(int i = 0; i < V; i++){
            if( !visited[i] && distances[i] == current){
                visited[i] = true;
                if(i == e){
                    return distances[i];
                }
                for(list<int>::const_iterator k = adj[i].begin(); 
                    k != adj[i].end(); k++){
                    if(distances[*k] == -1){
                        distances[*k] = current + 1;
                    }
                }
            }
        }
   }
   return 0;
}
};
//test the BFS
int main(){
    Graph g(64);
    for(int i = 0; i < 64; i++){
        g.add(i);
    }
    cout << g.BFS(1,2);
    return 0;     

}

1 个答案:

答案 0 :(得分:1)

以下代码使成员变量V处于未初始化状态,这可能是导致问题的原因。

Graph(int V){
    V = V; // The LHS is the same as the RHS, the argument to the function
           // not the class member variable.
    adjacent = new list<int>[V];
}

使用:

Graph(int V) : V(V) {
    adjacent = new list<int>[V];
}

为了使代码更易于阅读,请为参数使用不同的名称。

Graph(int inV) : V(inV) {
    adjacent = new list<int>[V];
}