用户将在图中输入节点的数量,然后输入一个整体的“行星”名称。然后他们将输入 where 是行星的名称,以及该行星的位置数。之后,各行如下形式:……。表示位置的名称,表示和…的邻居数。是 的邻居列表。
例如: 3 Venus 4 spaceport 2 beach disco beach 1 bar bar 1 spaceport disco 1 bar Neptune 3 spaceport 1 toy-factory toy-factory 0 weapons_depot 1 Weapon_depot Binary-2 2 spaceport 1 zero-one zero-one 1 spaceport
总会有一个太空港。然后我必须从太空港开始,列出哪些节点也无法获取。这是我认为我是 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;
}