One important thing to note is, simply doing BFS or DFS and picking the longest edge at every step would not work. The reason is, a shorter edge can produce longer path due to higher weight edges connected through it.

The idea is to use Backtracking. We start from given source, explore all paths from current vertex. We keep track of current distance from source. If distance becomes more than k, we return true. If a path doesn’t produces more than k distance, we backtrack.

How do we make sure that the path is simple and we don’t loop in a cycle? The idea is to keep track of current path vertices in an array. Whenever we add a vertex to path, we check if it already exists or not in current path. If it exists, we ignore the edge.

// This class represents a dipathted graph using

// adjacency list representation

classGraph

{

intV; // No. of vertices

// In a weighted graph, we need to store vertex

// and weight pair for every edge

list< pair<int, int> > *adj;

boolpathMoreThanKUtil(intsrc, intk, vector<bool> &path);

};

// Returns true if graph has path more than k length

boolGraph::pathMoreThanK(intsrc, intk)

{

// Create a path array with nothing included

// in path

vector<bool> path(V, false);

// Add source vertex to path

path[src] = 1;

returnpathMoreThanKUtil(src, k, path);

}

// Prints shortest paths from src to all other vertices

boolGraph::pathMoreThanKUtil(intsrc, intk, vector<bool> &path)

{

// If k is 0 or negative, return true;

if(k <= 0)

returntrue;

// Get all adjacent vertices of source vertex src and

// recursively explore all paths from src.

list<iPair>::iterator i;

for(i = adj[src].begin(); i != adj[src].end(); ++i)

{

// Get adjacent vertex and weight of edge

intv = (*i).first;

intw = (*i).second;

// If vertex v is already there in path, then

// there is a cycle (we ignore this edge)

if(path[v] == true)

continue;

// If weight of is more than k, return true

if(w >= k)

returntrue;

// Else add this vertex to path

path[v] = true;

// If this adjacent can provide a path longer

// than k, return true.

if(pathMoreThanKUtil(v, k-w, path))

returntrue;

// Backtrack

path[v] = false;

}

// If no adjacent could produce longer path, return

// false

returnfalse;

}

// Allocates memory for adjacency list

Graph::Graph(intV)

{

this->V = V;

adj = newlist<iPair> [V];

}

// Utility function to an edge (u, v) of weight w

voidGraph::addEdge(intu, intv, intw)

{

adj[u].push_back(make_pair(v, w));

adj[v].push_back(make_pair(u, w));

}

Modify the above solution to find weight of longest path from a given source.