Suppose that
A 1
/ \ / \
B C -- G 2 3 -- 7
/ \ \ \ <=> / \ \ \
D E F J 4 5 6 10
/ \ \ / \ \
H I K 8 9 11
Therefore, I can offer the solution of your problem, using the algorithm Depth first search.
/*
A - 1,
B - 2,
C - 3,
D - 4,
E - 5,
F - 6,
G - 7,
H - 8,
I - 9,
J - 10,
K - 11.
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
const int maximumSize=20;
int vertices, edges;
vector<int> visited0(maximumSize, 0);
vector<int> visited1(maximumSize, 0);
vector<int> graph[maximumSize];
vector<int> distances(maximumSize, 0);
vector<string> graphPaths;
string path;
vector<int> green(maximumSize, 0);
template<class Type>
void showContent1D(Type& input)
{
for(int i=0; i<input.size(); ++i)
{
cout<<input[i]<<", ";
}
return;
}
void showContentVectorString(vector<string>& input)
{
for(int i=0; i<input.size(); ++i)
{
cout<<input[i]<<", ";
}
return;
}
void createGraph()
{
cin>>vertices>>edges;
int vertex0, vertex1;
for(int i=1; i<=edges; ++i)
{
cin>>vertex0>>vertex1;
graph[vertex0].push_back(vertex1);
graph[vertex1].push_back(vertex0);
}
for(int i=1; i<=vertices; ++i)
{
cin>>green[i];
}
return;
}
void dfs0(int current, int previous)
{
if(visited0[current]==1)
{
return;
}
visited0[current]=1;
distances[current]=0;
for(int next : graph[current])
{
if(next==previous)
{
continue;
}
dfs0(next, current);
distances[current]=max(distances[current], distances[next]+1);
}
return;
}
void dfs1(int root, int current, int previous)
{
if(visited1[current]==1)
{
return;
}
visited1[current]=1;
if(green[current]==1)
{
if(distances[current]!=0)
{
path.append(to_string(current));
path.append("->");
}
else
{
path.append(to_string(current));
graphPaths.push_back(path);
path.pop_back();
}
}
for(int next : graph[current])
{
if(next==previous)
{
continue;
}
dfs1(root, next, current);
}
if(root==previous)
{
path.clear();
path.append(to_string(root));
path.append("->");
}
return;
}
void solve()
{
createGraph();
dfs0(1, 0);
dfs1(1, 1, 0);
cout<<"graphPaths: ";
showContentVectorString(graphPaths);
cout<<endl;
return;
}
int main()
{
solve();
return 0;
}
Input:
11 10
1 2
1 3
2 4
2 5
4 8
4 9
3 6
3 7
7 10
10 11
1
1
1
1
0
0
1
0
1
1
0
Here is the result:
graphPaths: 1->2->4->9,
If you will need an explanation of the solution, write the corresponding comment.