Skip to content

Instantly share code, notes, and snippets.

@basp1
Last active November 3, 2020 01:41
Show Gist options
  • Save basp1/c3a097c3e8988eda78999dd4ccb5a101 to your computer and use it in GitHub Desktop.
Save basp1/c3a097c3e8988eda78999dd4ccb5a101 to your computer and use it in GitHub Desktop.
Find all paths between 2 graph nodes (iterative depth first search)
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