mathball
Version:
A JavaScript library for Competitive Programming
101 lines (81 loc) • 3.33 kB
JavaScript
"use strict";
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Graph = function () {
function Graph(vertices) {
_classCallCheck(this, Graph);
this.noOfVertices = vertices;
this.Adjlist = new Map();
}
_createClass(Graph, [{
key: "addVertex",
value: function addVertex(vertexData) {
return this.Adjlist.set(vertexData, []);
}
}, {
key: "addEdge",
value: function addEdge(source, destination) {
return this.Adjlist.get(source).push(destination);
}
}, {
key: "printGraph",
value: function printGraph() {
return this.Adjlist;
}
}, {
key: "removeVertex",
value: function removeVertex(vertexName) {
if (this.Adjlist.size === 0) {
return "Empty Graph";
} else {
return this.Adjlist.delete(vertexName);
}
}
}, {
key: "removeEdge",
value: function removeEdge(vertexName, edgeName) {
if (this.Adjlist.size === 0) {
return "Empty Graph";
}
if (!this.Adjlist.get(vertexName)) {
return "Vertex does not exist in the Graph";
}
var location = this.Adjlist.get(vertexName).indexOf(edgeName);
if (location === -1) {
return "Edge not found!";
} else {
return this.Adjlist.get(vertexName).splice(location, 1).toString();
}
}
}, {
key: "bfs",
value: function bfs(startNode) {
if (!Array.from(this.Adjlist.keys()).includes(startNode)) {
return "Node doesn't exist in the Graph";
}
var visited = [];
var output = new Array();
for (var i = 0; i < this.noOfVertices; i++) {
visited.push(false);
}
var queue = [];
visited[startNode] = true;
queue.push(startNode);
while (queue.length > 0) {
var getQueueElement = queue.shift();
output.push(getQueueElement);
var getList = this.Adjlist.get(getQueueElement);
for (var _i = 0; _i < getList.length; _i++) {
var neighbour = getList[_i];
if (!visited[neighbour]) {
visited[neighbour] = true;
queue.push(neighbour);
}
}
}
return output;
}
}]);
return Graph;
}();
module.exports = Graph;