xxxxxxxxxx
106
class Graph {
constructor(v) {
this.num = v;
this.adjacencyList = new Map();
this.edgeList = [];
this.points = [];
this.visited = [];
this.path = ""
}
addVertex(v) {
this.adjacencyList.set(v, []);
}
addEdge(u, v) {
this.adjacencyList.get(u).push(v);
this.adjacencyList.get(v).push(u);
this.edgeList.push([u, v]);
}
getAdjList() {
let keys = this.adjacencyList.keys();
let text = "";
for (let key of keys) {
let values = this.adjacencyList.get(key);
let conc = "";
for (let v in values) {
let val = values[v];
if (v == values.length - 1) {
conc += "(" + val + ")";
} else {
conc += "(" + val + "),";
}
}
text += (key + " -> " + conc + "\n");
}
text = trim(text);
//print("Adjacency List\n"+text);
return text;
}
getEdgeList() {
let text = "[";
for (let i in this.edgeList) {
let item = this.edgeList[i];
if (i == this.edgeList.length - 1) {
text += "(" + item + ")";
} else {
text += "(" + item + "), ";
}
}
text += ']'
//print("Edge List\n"+text);
return text;
}
display() {
for (let poi in this.points) {
let p = this.points[poi];
noStroke();
if (this.visited[poi]) {
fill('green');
} else {
fill(0);
}
ellipse(p.x, p.y, 10);
fill(255, 0, 0);
if (p.x < width / 2) {
text(int(poi), p.x - 15, p.y + 5);
} else {
text(int(poi), p.x + 5, p.y + 5);
}
}
fill(0);
let edgeList = this.edgeList;
let points = this.points;
for (let edge of edgeList) {
let u0, u1;
if (edge[0] >= 'A' && edge[0] <= 'Z') {
u0 = unchar(edge[0]) - 65
} else {
u0 = edge[0]
}
if (edge[1] >= 'A' && edge[1] <= 'Z') {
u1 = unchar(edge[1]) - 65
} else {
u1 = edge[1]
}
//print(edge);
drawLine(points[u0].x, points[u0].y, points[u1].x, points[u1].y)
// text(edge[2], (points[u0].x + points[u1].x) / 2, (points[u0].y + points[u1].y) / 2);
}
}
update() {
this.num = this.adjacencyList.size;
let n = this.num;
for (let i = 0; i < n; i++) {
let angle = i * TWO_PI / n;
let v = p5.Vector.fromAngle(angle);
v.mult(-width * 0.3);
v.add(width / 2, height * 3 / 7);
this.points.push(v);
}
for (let i = 0; i < this.num; i++) {
this.visited[i] = false;
}
}
runBFS(){
}
}