public static int[] BfsDescendant <TNode, TEdge>(this ITreeGraph <TNode, TEdge> tree, bool skipFirst = false) where TNode : ITreeNode <TEdge> where TEdge : IGraphEdge { var arr = tree.AsArray(); var res = new int[arr.Length - (skipFirst ? 1 : 0)]; int tar = 0; if (skipFirst) { foreach (var e in arr[tree.Root].Children) { res[tar++] = e.To; } } else { res[tar++] = tree.Root; } int cur = 0; while ((uint)tar < (uint)res.Length) { foreach (var e in arr[res[cur++]].Children) { res[tar++] = e.To; } } return(res); }
public static int[] DfsDescendant <TNode, TEdge>(this ITreeGraph <TNode, TEdge> tree, bool skipFirst = false) where TNode : ITreeNode <TEdge> where TEdge : IGraphEdge { var arr = tree.AsArray(); var res = new int[arr.Length - (skipFirst ? 1 : 0)]; int cur = 0; var stack = new Stack <int>(arr.Length); if (skipFirst) { var children = arr[tree.Root].Children; for (int i = children.Length - 1; i >= 0; i--) { stack.Push(children[i].To); } } else { stack.Push(tree.Root); } while (stack.TryPop(out var ix)) { res[cur++] = ix; var children = arr[ix].Children; for (int i = children.Length - 1; i >= 0; i--) { stack.Push(children[i].To); } } return(res); }
public static int[] DescendantsCounts <TNode, TEdge>(this ITreeGraph <TNode, TEdge> tree) where TNode : ITreeNode <TEdge> where TEdge : IGraphEdge { var treeArr = tree.AsArray(); var res = new int[treeArr.Length]; var stack = new Stack <(int v, int ci)>(treeArr.Length); stack.Push((tree.Root, 0)); while (stack.TryPop(out var tup)) { var(v, ci) = tup; var children = treeArr[v].Children; if (ci == 0) { res[v] = 1; } else { res[v] += res[children[ci - 1].To]; } if (ci < children.Length) { stack.Push((v, ci + 1)); stack.Push((children[ci].To, 0)); } } return(res); }