字典
function Dictionary() {
this.items = {};
Dictionary.prototype.set = function (key, value) {
this.items[key] = value;
};
Dictionary.prototype.has = function (key) {
return this.items.hasOwnProperty(key);
};
Dictionary.prototype.remove = function (key) {
if (!this.has(key)) return false;
delete this.items[key];
return true;
};
Dictionary.prototype.get = function (key) {
return this.has(key) ? this.items[key] : undefined;
};
Dictionary.prototype.keys = function () {
return Object.keys(this.items);
};
Dictionary.prototype.size = function () {
return this.keys.length;
};
Dictionary.prototype.clear = function () {
this.items = {};
};
}
图
需要用到队列
function Graph() {
// 顶点
this.vertexes = [];
this.edges = new Dictionary();
Graph.prototype.addVertex = function (v) {
this.vertexes.push(v);
this.edges.set(v, []);
};
Graph.prototype.addEdge = function (v1, v2) {
this.edges.get(v1).push(v2);
this.edges.get(v2).push(v1);
};
/**
* 定义颜色表示顶点是否被访问过
* 白色:表示该顶点还没有被访问
* 灰色:表示该顶点被访问过,但并未被探索过
* 黑色:表示该顶点被访问过且被探索过
* */
Graph.prototype.initColor = function () {
const colors = [];
for (let i = 0; i < this.vertexes.length; i++) {
colors[this.vertexes[i]] = "white";
}
return colors;
};
// 广度优先搜索
Graph.prototype.bfs = function (initV, handler) {
// 1. 初始化颜色
const colors = this.initColor();
// 2. 创建队列
const queue = new Queue();
// 3. 将顶点加入到队列中
queue.enqueue(initV);
// 4. 循环从队列中取出元素
while (!queue.isEmpty()) {
const v = queue.dequeue();
const vList = this.edges.get(v);
colors[v] = "gray";
for (let i = 0; i < vList.length; i++) {
const e = vList[i];
if (colors[e] === "white") {
colors[e] = "gray";
queue.enqueue(e);
}
}
handler(v);
colors[v] = "black";
}
};
// 深度优先搜索
Graph.prototype.dfs = function (initV, handler) {
// 1. 初始化颜色
const colors = this.initColor();
// 2. 从某个顶点开始依次递归访问
this.dfsVisit(initV, colors, handler);
};
Graph.prototype.dfsVisit = function (v, colors, handler) {
// 1. 先将颜色设置为灰色
colors[v] = "gray";
// 2. 处理v顶点
handler(v);
// 3. 访问v相连的顶点
const vList = this.edges.get(v);
for (let i = 0; i < vList.length; i++) {
const e = vList[i];
if (colors[e] === "white") {
this.dfsVisit(e, colors, handler);
}
}
// 4. 将v设置成黑色
colors[v] = "black";
};
}