-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPathOfMoreThanKLength.cs
More file actions
41 lines (29 loc) · 1.2 KB
/
Copy pathPathOfMoreThanKLength.cs
File metadata and controls
41 lines (29 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
using System.Collections.Generic;
using AlgorithmsAndDataStructures.Algorithms.Graph.Common;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.Backtracking;
public class PathOfMoreThanKLength
{
public (bool hasPath, HashSet<int> path) GetPathOfMoreThanKLength(WeightedGraphVertex[] graph, int startVertex,
int targetWeight)
{
if (graph is null) return (false, new HashSet<int>());
var path = new HashSet<int> { startVertex };
var hasPath = Dfs(graph, startVertex, 0, targetWeight, path);
return (hasPath, hasPath ? path : new HashSet<int>());
}
private bool Dfs(WeightedGraphVertex[] graph, int currentVertexIndex, int currentWeight, int targetWeight,
ISet<int> path)
{
var currentVertex = graph[currentVertexIndex];
if (currentWeight >= targetWeight) return true;
foreach (var edge in currentVertex.Edges)
if (!path.Contains(edge.To))
{
path.Add(edge.To);
var isPath = Dfs(graph, edge.To, currentWeight + edge.Weight, targetWeight, path);
if (isPath) return true;
path.Remove(edge.To);
}
return false;
}
}