Complete the code to create a graph node with a value and an empty list of neighbors.
class GraphNode { constructor(value) { this.value = value; this.neighbors = [1]; } }
The neighbors of a graph node are stored in an array to hold multiple connected nodes.
Complete the code to add an edge from one node to another in an undirected graph.
function addEdge(node1, node2) {
node1.neighbors.push([1]);
node2.neighbors.push(node1);
}To add an edge, node2 is added to node1's neighbors list.
Fix the error in the code to check if a graph has a cycle using a visited set.
function hasCycle(node, visited = new Set()) {
if (visited.has(node)) {
return [1];
}
visited.add(node);
for (const neighbor of node.neighbors) {
if (hasCycle(neighbor, visited)) {
return true;
}
}
return false;
}If the node is already visited, it means a cycle exists, so return true.
Fill both blanks to create a function that counts the total edges in an undirected graph.
function countEdges(graph) {
let count = 0;
for (const node of graph) {
count += node.[1].length;
}
return count [2] 2;
}Count all neighbors for each node, then divide by 2 because edges are counted twice in an undirected graph.
Fill all three blanks to create a function that finds if a path exists between two nodes using DFS.
function pathExists(start, target, visited = new Set()) {
if (start.value === [1]) return true;
visited.add(start);
for (const neighbor of start.[2]) {
if (!visited.has(neighbor) && pathExists(neighbor, [3], visited)) {
return true;
}
}
return false;
}Check if start node's value equals target's value, iterate over neighbors, and recursively check path existence.
