-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDepthFirstSearch.cs
More file actions
69 lines (55 loc) · 2.15 KB
/
DepthFirstSearch.cs
File metadata and controls
69 lines (55 loc) · 2.15 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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System.Collections.Generic;
using System.Linq;
using AlgorithmsAndDataStructures.DataStructures.Graph;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.Search;
public class DepthFirstSearch
{
#pragma warning disable CA1822 // Mark members as static
public List<int> Traverse(GraphVertex<int>[] graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return new List<int>(0);
var result = new HashSet<int>();
var visited = new HashSet<int>();
TraverseInternal(0, graph, result, visited);
return result.ToList();
}
private static void TraverseInternal(int node, IReadOnlyList<GraphVertex<int>> graph, ISet<int> result,
ISet<int> visited)
{
result.Add(graph[node].Value);
visited.Add(node);
var notVisitedAdjacentNodes = graph[node].AdjacentVertices
.Where(arg => !visited.Contains(arg));
foreach (var adjacentNode in notVisitedAdjacentNodes) TraverseInternal(adjacentNode, graph, result, visited);
}
#pragma warning disable CA1822 // Mark members as static
public List<int> TraverseNonRecursive(GraphVertex<int>[] graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return new List<int>(0);
var result = new HashSet<int>();
var visited = new HashSet<int>();
var stack = new Stack<int>();
stack.Push(0);
result.Add(graph[0].Value);
while (true)
{
if (!stack.Any()) break;
var currentVertex = stack.Peek();
var adjacentNodes = graph[currentVertex].AdjacentVertices;
if (!adjacentNodes.Except(visited).Any())
stack.Pop();
else
for (var i = 0; i < adjacentNodes.Count; i++)
if (!visited.Contains(adjacentNodes[i]))
{
visited.Add(adjacentNodes[i]);
stack.Push(adjacentNodes[i]);
result.Add(graph[adjacentNodes[i]].Value);
break;
}
}
return result.ToList();
}
}