UNPKG

adt-legacy-js

Version:

Faster way to implement Auxiliary Data Types

89 lines (82 loc) 2.26 kB
class Vertex { constructor(label) { this.label = label; } } class Graph { constructor(v) { this.vertices = v; this.edges = 0; this.adj = []; this.edgeTo = []; for (var i = 0; i < this.vertices; ++i) { this.adj[i] = []; } } addEdge(v,w) { this.adj[v].push(w); this.adj[w].push(v); this.edges++; } showGraph() { let arr = []; for (var i=0; i< this.vertices;++i) { arr[i] = `${i} =>` for(var j=0; j<this.vertices; ++j) { if(this.adj[i][j] !==undefined) { arr[i] += `${this.adj[i][j]} ` } } } return arr; } #searchDfs(v,marked, dataArr = []) { marked[v] = true; if (this.adj[v] !== undefined) { dataArr.push(v); for (let w of this.adj[v]) { if(!marked[w]) { this.#searchDfs(w, marked, dataArr); } } } return dataArr; } dfs(v) { let marked = []; for (var i=0; i<this.vertices; ++i) { marked[i] = false; } const finalData = this.#searchDfs(v, marked); return finalData; } #searchBfs(v,marked,dataArr = []) { var queue = []; marked[v] = true; queue.push(v); dataArr.push(v); while(queue.length > 0) { var s = queue.shift(); if(this.adj[s] !== undefined) { for (let w of this.adj[s]) { if(!marked[w]) { this.edgeTo[w] = s; dataArr.push(w); marked[w] = true; queue.push(w); } } } } return dataArr; } bfs(v) { let marked = []; for (var i=0; i< this.vertices; i++) { marked[i] = false; } const finalData = this.#searchBfs(v,marked); return finalData; } } module.exports = Graph;