Skip to content

Instantly share code, notes, and snippets.

@Millsky
Created January 23, 2019 13:54
Show Gist options
  • Save Millsky/9df02a5df1834d1a01d823793a26fba9 to your computer and use it in GitHub Desktop.
Save Millsky/9df02a5df1834d1a01d823793a26fba9 to your computer and use it in GitHub Desktop.
/* Build an adjacency matrix for a super simple tree a -> b,c */
const m = [
[0, 1, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]
];
/* Data at each node */
const v = [0,1,2,3,4];
/* Map over the 0-1 and get all the indexes of the 1s */
const getChildrenAM = (node) => {
return node.map((item, index) => {
return item === 1 ? index : null;
}).filter(item => item !== null)
}
/* DFS */
const DFS = (g) => {
return [v[0], ...g.map((n, i) => {
return getChildrenAM(n).map((ci) => {
return v[ci];
});
}).flatMap((a) => a)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment