You are viewing a single comment's thread. Return to all comments →
Typescript solution. it passes all tests. (DFS)
function bfs(graph: number[][], start: number):number[] { const queue: number[] = [start]; const visited = new Set<number>(); while (queue.length > 0) { const selectedNode = queue.pop(); if (!visited.has(selectedNode)) { visited.add(selectedNode); for (let node of graph) { if (node[0] == selectedNode) { queue.push(node[1]); } if (node[1] == selectedNode) { queue.push(node[0]); } } } } return Array.from(visited) } function componentsInGraph(gb: number[][]): number[] { // Write your code here const nodes = new Set<number>(); for (let g of gb) { nodes.add(g[0]); nodes.add(g[1]); } let max = 0; let min = nodes.size ; nodes.forEach((index) => { // if(index > nodes.size / 2){return} const bfsssss = bfs(gb, index); bfsssss.forEach(b => nodes.delete(b)); const value = bfsssss.length; if (value > max) { max = value; } if (value < min && value > 1) { min = value; } }) // console.log([min,max]); return [min, max]; }
Seems like cookies are disabled on this browser, please enable them to open this website
Components in a graph
You are viewing a single comment's thread. Return to all comments →
Typescript solution. it passes all tests. (DFS)