Skip to content

Instantly share code, notes, and snippets.

@rakibulalam
Last active May 28, 2022 21:47
Show Gist options
  • Save rakibulalam/01782d1603751cbd35e1bd568c0dc286 to your computer and use it in GitHub Desktop.
Save rakibulalam/01782d1603751cbd35e1bd568c0dc286 to your computer and use it in GitHub Desktop.
BFS: Shortest Reach in a Graph Hacker Rank
class Node {
constructor(value) {
this.value = 0;
this.label = 0;
this.distance = -1;
this.visited = false;
this.edges = [];
}
addEdge(node) {
this.edges.push(node);
node.edges.push(this);
}
}
class Graph {
constructor(n) {
this.size = n;
this.graph = {};
}
addNode(from, to) {
let node1 = this.graph[from], node2 = this.graph[to];
if (!node1) {
node1 = new Node(from)
this.graph[from] = node1;
}
if (!node2) {
node2 = new Node(to);
this.graph[to] = node2;
}
node1.addEdge(node2);
}
addNodes(nodes) {
for(let i=1; i<=this.size; i++)
{
this.graph[i]=new Node(i);
}
nodes.forEach((value) => {
const [x, y] = value.split(' ')
this.addNode(x, y)
}
);
}
BFS(startNode) {
if (!startNode) return null;
startNode = this.graph[startNode];
startNode.visited = true;
startNode.distance = 0;
const queue = [startNode];
while (queue.length) {
const { value: current, edges, distance, label } = queue.shift();
for (let i = 0; i < edges.length; i++) {
const node = edges[i];
if (!node.visited) {
node.label = label + 1;
node.distance = 6 * node.label;
node.visited = true;
queue.push(node);
}
}
}
return Object.keys(this.graph).map((key)=>this.graph[key].distance).filter((v)=>v!==0).join(' ')
}
};
function processData(input) {
var lines = input.split('\n');
var T = parseInt(lines[0]);
var index = 1;
for (var i = 0; i < T; i++) {
var N = parseInt(lines[index].split(' ')[0]);
var M = parseInt(lines[index].split(' ')[1]);
var graphInput = lines.slice(index + 1, M + index + 1);
index += M + 1;
var S = parseInt(lines[index]);
index += 1;
var graph = new Graph(N);
graph.addNodes(graphInput);
console.log(graph.BFS(S));
}
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment