DFS on a Weighted Graph

Problem Implement depth-first search over a weighted graph and apply it to a downstream task: determine whether a path exists between two nodes and accumulate the total edge weight along the path DFS discovers.

Input / Output

  • Input: a graph as an adjacency list whose entries are (neighbour, weight) pairs, plus a source node A and a target node B.
  • Output: whether B is reachable from A and the summed weight of the first path DFS finds (extension: the path itself).

Constraints

  • Up to ~10^4 nodes and edges.
  • Weights sit on the edges but do not steer the traversal — DFS follows adjacency order, not weight order.
  • The graph may be disconnected and may contain cycles; confirm whether it is directed or undirected, since undirected edges must be stored both ways.

Example

  • Edges A→B (5), A→C (1), C→B (1). DFS from A, visiting neighbours in listed order, finds A→B with weight 5 and returns immediately — even though A→C→B costs only 2. The first path DFS finds is not the cheapest, and that gap is the point of the question.
asked …
LeaderboardSalaryAccount