class GraphNode {
constructor(val) {
this.val = val;
this.neighbors = [];
}
}
let a = new GraphNode("a");
let b = new GraphNode("b");
let c = new GraphNode("c");
let d = new GraphNode("d");
let e = new GraphNode("e");
let f = new GraphNode("f");
a.neighbors = [b, c, e];
c.neighbors = [b, d];
e.neighbors = [a];
f.neighbors = [e];
The row index will corespond to the source of an edge and the column index will correspond to the edges destination.
matrix[i][j]
may not be the same as matrix[j][i]
let matrix = [
A | B | C | D | E | F | |
---|---|---|---|---|---|---|
A | [True, | True, | True, | False, | True, | False] |
B | [False, | True, | False, | False, | False, | False] |
C | [False, | True, | True, | True, | False, | False] |
D | [False, | False, | False, | True, | False, | False] |
E | [True, | False, | False, | False, | True, | False] |
F | [False, | False, | False, | False, | True, | True] |
];
Seeks to solve the shortcomings of the matrix implementation. It uses an object where keys represent node labels and values associated with that key are the adjacent nodes.
class GraphNode {
constructor(val) {
this.val = val;
this.neighbors = [];
}
}
let a = new GraphNode("a");
let b = new GraphNode("b");
let c = new GraphNode("c");
let d = new GraphNode("d");
let e = new GraphNode("e");
let f = new GraphNode("f");
a.neighbors = [e, c, b];
c.neighbors = [b, d];
e.neighbors = [a];
f.neighbors = [e];
function depthFirstRecur(node, visited = new Set()) {
if (visited.has(node.val)) return;
console.log(node.val);
visited.add(node.val);
node.neighbors.forEach((neighbor) => {
depthFirstRecur(neighbor, visited);
});
}
depthFirstRecur(f); // starting with f as it is a node that can reach all other nodes
>function depthFirstIter(node) {
let visited = new Set();
let stack = [node];
while (stack.length) {
let node = stack.pop();
if (visited.has(node.val)) continue;
console.log(node.val);
visited.add(node.val);
stack.push(...node.neighbors);
}
}
depthFirstIter(f);
Remember that the nodes are stored as strings in an array in an object.
>function depthFirstRecur(node, graph, visited = new Set()) {
if (visited.has(node)) return;
console.log(node);
visited.add(node);
graph[node].forEach((neighbor) => {
depthFirstRecur(neighbor, graph, visited);
});
}
depthFirstRecur("f", graph);
>function depthFirst(graph) {
let visited = new Set();
for (let node in graph) {
_depthFirstRecur(node, graph, visited);
}
}
function _depthFirstRecur(node, graph, visited) {
if (visited.has(node)) return;
console.log(node);
visited.add(node);
graph[node].forEach((neighbor) => {
_depthFirstRecur(neighbor, graph, visited);
});
}
depthFirst(graph);