-
Notifications
You must be signed in to change notification settings - Fork 299
/
Copy pathDepthFirst.cs
38 lines (31 loc) · 907 Bytes
/
DepthFirst.cs
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
using System.Collections.Generic;
using Advanced.Algorithms.DataStructures.Graph;
namespace Advanced.Algorithms.Graph;
/// <summary>
/// Depth First Search.
/// </summary>
public class DepthFirst<T>
{
/// <summary>
/// Returns true if item exists.
/// </summary>
public bool Find(IGraph<T> graph, T vertex)
{
return Dfs(graph.ReferenceVertex, new HashSet<T>(), vertex);
}
/// <summary>
/// Recursive DFS.
/// </summary>
private bool Dfs(IGraphVertex<T> current,
HashSet<T> visited, T searchVetex)
{
visited.Add(current.Key);
if (current.Key.Equals(searchVetex)) return true;
foreach (var edge in current.Edges)
{
if (visited.Contains(edge.TargetVertexKey)) continue;
if (Dfs(edge.TargetVertex, visited, searchVetex)) return true;
}
return false;
}
}