Last active
November 3, 2020 01:41
-
-
Save basp1/c3a097c3e8988eda78999dd4ccb5a101 to your computer and use it in GitHub Desktop.
Find all paths between 2 graph nodes (iterative depth first search)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
namespace CircuitSelector | |
{ | |
public static class Graph | |
{ | |
// use LinkedHashSet from http://stackoverflow.com/a/31419199/1312837 with some additions | |
public static List<List<int>> FindAllPaths(AdjacentMatrix adj, int begin, int end) | |
{ | |
var nodes = new Stack<int>(); | |
nodes.Push(begin); | |
var depth = new Stack<int>(); | |
depth.Push(begin); | |
var path = new LinkedHashSet<int>(); | |
var paths = new List<List<int>>(); | |
while (nodes.Count > 0) | |
{ | |
var cur = nodes.Pop(); | |
var lvl = depth.Pop(); | |
while (path.Count > 0 && path.Last().Value != lvl) | |
{ | |
path.RemoveLast(); | |
} | |
path.Add(cur); | |
bool hasNew = false; | |
foreach (int neighbor in adj.Row(cur)) | |
{ | |
if (path.Contains(neighbor)) | |
{ | |
continue; | |
} | |
if (end == neighbor) | |
{ | |
var res = new List<int>(path); | |
res.Add(end); | |
paths.Add(res); | |
continue; | |
} | |
else | |
{ | |
hasNew = true; | |
nodes.Push(neighbor); | |
depth.Push(cur); | |
} | |
} | |
if (!hasNew) | |
{ | |
path.RemoveLast(); | |
} | |
} | |
return paths; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment