I can offer to consider the concrete graph (tree), where vertices are numbers but not letters. The problem, you want to solve, supposes applying the Depth First Search algorithm as you have shown in your requirement.
Assume, we have the graph (tree):

Relatively of this graph, the max path from one vertex to another vertex must be calculated.
Here is the solution of your problem.
#include <iostream>
#include <vector>
using namespace std;
const int maximumSize=10;
vector<int> visited(maximumSize, 0), distances(maximumSize, 0);
vector<int> graph[maximumSize];
int vertices, edges;
void showContentVector1D(vector<int>& input)
{
for(int index=0; index<input.size(); ++index)
{
cout<<input[index]<<", ";
}
return;
}
void createGraph()
{
cin>>vertices>>edges;
int vertex0, vertex1;
for(int edge=1; edge<=edges; ++edge)
{
cin>>vertex0>>vertex1;
graph[vertex0].push_back(vertex1);
graph[vertex1].push_back(vertex0);
}
return;
}
void depthFirstSearch(int currentVertex, int previousVertex)
{
if(visited[currentVertex]==1)
{
return;
}
visited[currentVertex]=1;
distances[currentVertex]=0;
for(int nextVertex : graph[currentVertex])
{
if(nextVertex==previousVertex)
{
continue;
}
depthFirstSearch(nextVertex, currentVertex);
distances[currentVertex]=max(distances[currentVertex], distances[nextVertex]+1);
}
return;
}
void solve()
{
createGraph();
depthFirstSearch(1, 0);
cout<<"distances <- ";
showContentVector1D(distances);
cout<<endl;
return;
}
int main()
{
solve();
return 0;
}
Input:
6 5
1 4
2 4
3 4
4 5
5 6
The first line in the input is 6 5
, where 6
is the quantity of vertices in a graph and 5
is the quantity of edges in a graph.
1 4
, 2 4
, 3 4
, 4 5
, 5 6
are edges of an provided undirected graph.
Output:
distances <- 0, 3, 0, 0, 2, 1, 0, 0, 0, 0,
The number 3
is assigned into the index 1
which corresponds to the vertex 1
of the provided undirected graph (tree). Also in the concrete indices the distances 2
and 1
are assigned. Those indices are 4
and 5
correspondingly. As you can see the maximum distance is 3
from the vertex 1
to the vertex 6
.