2012-12-10 29 views
0

用户将输入图形中的节点数,然后输入总体“行星”名称。那么他们将输入 这里是行星的名称,并且是这个星球上的位置数量。 然后,行后面,每个形式: ...。 指示位置的名称,指示和...的邻居的数量。是一个邻居列表。通过有向图查看错误C++分割错误

例如:金星4 航空基地2海滩迪斯科 海滩1巴 条1个航空基地 迪斯科1巴 海王星3 航空基地1玩具厂 玩具厂0 weapons_depot 1 weapons_depot 选择Binary- 2 2 航空基地1 0-1 0-1 1航空基地

总是会有一个航空基地。然后我必须从太空港开始,列出哪些节点不能得到。这是我认为我是Seg错误的部分。它会在尝试输出节点时编译seg故障。

下面是代码:

#include <iostream> 
#include <map> 
#include <vector> 
using namespace std; 
bool path(int x, int y, vector<vector<bool> > graph); 

int main() 
{ 
    int num_planets; 
    cin>>num_planets; 

    for (int m=0; m<num_planets; m++) 
    { 
    string planet; 
    int num_locations; 

    cin>>planet; 
    cin>>num_locations; 
    map<string, int> m_planet; 
    vector<vector<bool> > graph; 
    graph.resize(num_locations); 

    for (int n=0; n<num_locations; n++) 
    { 
     graph[n].resize(num_locations); 
    } 
    for(int k=0; k<num_locations; k++) 
    { 
     for (int j=0; j<num_locations; j++) 
     { 
     graph[k][j] = false; 
     } 
    } vector<vector<string> > connections; 

    vector<string> places; 
    for (int o=0; o<num_locations; o++) 
    { 
     string place; 

     cin>>place; 
     places.push_back(place); 
     m_planet[place] = o; 
     int edges; 

     cin>>edges; 
     connections.resize(num_locations); 
     connections[o].resize(edges); 

     for (int p=0; p<edges; p++) 
     { 
     string connect; 
     cin>>connect; 
     connections[o][p]=connect; 
     } 
    } 

    for (int q=0; q<num_locations; q++) 
    { 
     for (int r=0; r<connections[q].size(); r++) 
     { 
     int from, to; 
     from = m_planet[places[q]]; 
     to = m_planet[connections[q][r]]; 
     graph[from][to] =true; 
     } 
    } 

    cout<<"In planet "<<planet<<":"<<endl; 

    int num_paths = 1; 
    for(int s=1; s<num_locations; s++) 
    { 
     bool route; 
     route = path(0, s, graph); 

     if(route == false) 
     { 
     cout<<places[s]<<"unreachable from the#" 
      <<places[0]<<"."<<endl; 
     } 

     else 
     { 
     num_paths++; 
     } 
    } 

    if (num_paths == num_locations) 
    { 
     cout<<"All locations reachable from the#"<<places[0]<<"."<<endl; 
    } 
    } 

    return 0; 
} 

    bool path(int x, int y, vector<vector<bool> > graph) 
    { 
    for (int m=0; m<graph[x].size(); m++) 
    { 
     if(graph[x][m] == true) 
     { 
     if (graph[x][m] == y) 
     { 
      return true; 
     } 

     else 
     { 
      return path(m, y, graph); 
     } 
     } 
    } 

    return false; 
    } 
+0

如果它segfaults它也将能够告诉你在哪里(backtrace)。在调试器中运行它 – gvd

回答

0

您将要覆盖NUM_LOCATIONS,但试图用它来访问这两个方面。这意味着,除非用户每次输入相同的值,否则将遇到问题,因为其中一个维度将超出范围。

为每个维度保留单独的变量。