Given an undirected weighted graph with V vertices numbered from 0 to V - 1 and an integer k, find if there exists a simple path starting from vertex 0 whose total path weight is greater than or equal to k. A simple path is a path in which no vertex is visited more than once.
Examples:
Input: V = 5, edges[][] = [[0, 1, 4], [0, 2, 8], [1, 4, 6], [2, 3, 2], [4, 3, 10]], k = 8 Output: true Explanation: One possible simple path is 0 -> 1 -> 4. The total path weight is 4 + 6 = 10, which is greater than or equal to k = 8. Hence, a valid path exists and the answer is true.
Input: V = 4 , edges[][] = [[0, 1, 5], [1, 2, 1], [2, 3, 1]], k = 8 Output: false Explanation: There exists no path which has a distance of 8.
[Expected Approach] Using DFS and Backtracking - O(V!) Time and O(V) Space
Since a simple path cannot contain repeated vertices, we can explore all possible paths using DFS while marking visited vertices. As we traverse an edge, we reduce the remaining weight required by its weight. If the remaining weight becomes non-positive, a valid path has been found. After exploring a path, we backtrack by unmarking the current vertex so that it can be used in other potential paths.
Step By Step Implementation:
Build an adjacency list from the given edge list.
Create a visited array to avoid revisiting vertices and maintain a simple path.
Start DFS from vertex 0 with the required path length k.
For every unvisited neighbor, check if its edge weight is enough to satisfy the remaining length.
Otherwise, continue DFS with the remaining weight reduced by the edge weight.
If any DFS call succeeds, return true.
Backtrack by unmarking the current vertex after exploring all paths through it.
Return false if no valid path is found.
C++
#include<iostream>#include<vector>usingnamespacestd;booldfs(intu,intk,vector<vector<pair<int,int>>>&adj,vector<bool>&vis){// Required path length has been achieved.if(k<=0)returntrue;vis[u]=true;for(auto&[v,wt]:adj[u]){// Skip already visited vertices.if(vis[v])continue;// Taking this edge alone satisfies the requirement.if(wt>=k)returntrue;// Explore further with reduced remaining length.if(dfs(v,k-wt,adj,vis))returntrue;}// Backtrack for other possible paths.vis[u]=false;returnfalse;}boolpathMoreThanK(intV,vector<vector<int>>&edges,intk){vector<vector<pair<int,int>>>adj(V);for(auto&e:edges){adj[e[0]].push_back({e[1],e[2]});adj[e[1]].push_back({e[0],e[2]});}vector<bool>vis(V,false);returndfs(0,k,adj,vis);}intmain(){intV=5;vector<vector<int>>edges={{0,1,4},{0,2,8},{1,4,6},{2,3,2},{4,3,10}};intk=8;cout<<(pathMoreThanK(V,edges,k)?"true":"false");return0;}
Java
importjava.util.ArrayList;importjava.util.List;classGFG{staticbooleandfs(intu,intk,List<List<int[]>>adj,boolean[]vis){// Required path length has been achieved.if(k<=0)returntrue;vis[u]=true;for(int[]edge:adj.get(u)){intv=edge[0];intwt=edge[1];// Skip already visited vertices.if(vis[v])continue;// Taking this edge alone satisfies the requirement.if(wt>=k)returntrue;// Explore further with reduced remaining length.if(dfs(v,k-wt,adj,vis))returntrue;}// Backtrack for other possible paths.vis[u]=false;returnfalse;}staticbooleanpathMoreThanK(intV,int[][]edges,intk){List<List<int[]>>adj=newArrayList<>();for(inti=0;i<V;i++)adj.add(newArrayList<>());for(int[]e:edges){adj.get(e[0]).add(newint[]{e[1],e[2]});adj.get(e[1]).add(newint[]{e[0],e[2]});}boolean[]vis=newboolean[V];returndfs(0,k,adj,vis);}publicstaticvoidmain(String[]args){intV=5;int[][]edges={{0,1,4},{0,2,8},{1,4,6},{2,3,2},{4,3,10}};intk=8;System.out.println(pathMoreThanK(V,edges,k));}}
Python
defdfs(u,k,adj,vis):# Required path length has been achieved.ifk<=0:returnTruevis[u]=Trueforv,wtinadj[u]:# Skip already visited vertices.ifvis[v]:continue# Taking this edge alone satisfies the requirement.ifwt>=k:returnTrue# Explore further with reduced remaining length.ifdfs(v,k-wt,adj,vis):returnTrue# Backtrack for other possible paths.vis[u]=FalsereturnFalsedefpathMoreThanK(V,edges,k):adj=[[]for_inrange(V)]foru,v,winedges:adj[u].append((v,w))adj[v].append((u,w))vis=[False]*Vreturndfs(0,k,adj,vis)V=5edges=[[0,1,4],[0,2,8],[1,4,6],[2,3,2],[4,3,10]]k=8print(str(pathMoreThanK(V,edges,k)).lower())
C#
usingSystem;usingSystem.Collections.Generic;classGFG{staticboolDFS(intu,intk,List<List<(int,int)>>adj,bool[]vis){// Required path length has been achieved.if(k<=0)returntrue;vis[u]=true;foreach(varedgeinadj[u]){intv=edge.Item1;intwt=edge.Item2;// Skip already visited vertices.if(vis[v])continue;// Taking this edge alone satisfies the requirement.if(wt>=k)returntrue;// Explore further with reduced remaining length.if(DFS(v,k-wt,adj,vis))returntrue;}// Backtrack for other possible paths.vis[u]=false;returnfalse;}staticboolPathMoreThanK(intV,int[][]edges,intk){List<List<(int,int)>>adj=new();for(inti=0;i<V;i++)adj.Add(newList<(int,int)>());foreach(vareinedges){adj[e[0]].Add((e[1],e[2]));adj[e[1]].Add((e[0],e[2]));}bool[]vis=newbool[V];returnDFS(0,k,adj,vis);}staticvoidMain(){intV=5;int[][]edges={newint[]{0,1,4},newint[]{0,2,8},newint[]{1,4,6},newint[]{2,3,2},newint[]{4,3,10}};intk=8;Console.WriteLine(PathMoreThanK(V,edges,k).ToString().ToLower());}}
JavaScript
functiondfs(u,k,adj,vis){// Required path length has been achieved.if(k<=0)returntrue;vis[u]=true;for(const[v,wt]ofadj[u]){// Skip already visited vertices.if(vis[v])continue;// Taking this edge alone satisfies the requirement.if(wt>=k)returntrue;// Explore further with reduced remaining length.if(dfs(v,k-wt,adj,vis))returntrue;}// Backtrack for other possible paths.vis[u]=false;returnfalse;}functionpathMoreThanK(V,edges,k){constadj=Array.from({length:V},()=>[]);for(const[u,v,w]ofedges){adj[u].push([v,w]);adj[v].push([u,w]);}constvis=newArray(V).fill(false);returndfs(0,k,adj,vis);}// Driver CodeconstV=5;constedges=[[0,1,4],[0,2,8],[1,4,6],[2,3,2],[4,3,10]];constk=8;console.log(pathMoreThanK(V,edges,k));