图
一般是一组顶点(vertex)和一组(eage)边
按照邻接矩阵来表示,如果是稀疏图(就是图中有很多0),就表示我们用了大量的内存来存储压根儿就没有的边,这是邻接矩阵的一个缺点
图的实现
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.toString = function () {
let resstr = '';
for (let i = 0; i < this.vertexes.length; i++) {
resstr += this.vertexes[i] + '->';
let temp = this.edges.get(this.vertexes[i]);
for (let j = 0; j < temp.length; j++) {
resstr += temp[j] + ' ';
}
resstr += "\n";
}
return resstr;
}
Graph.prototype.initializeColor = function () {
let colors = [];
for (let i = 0; i < this.vertexes.length; i++) {
colors[this.vertexes[i]] = 'white';
}
return colors;
}
Graph.prototype.BFS = function(initV, handler) {//基于队列
let colors = this.initializeColor();//初始化颜色
let queue = new Queue();
queue.enqueue(initV);
while (!queue.isEmpty()) {
let v = queue.dequeue();
let vlist = this.edges.get(v);
colors[v] = "gray";
for (let i = 0; i < vlist.length; i++) {
let temp = vlist[i]
if(colors[temp] == 'white'){
colors[temp] = "gray";
queue.enqueue(temp);
}
}
handler(v);//访问顶点
colors[v] = 'black';
}
}
Graph.prototype.DFS = function(initV, handler) {//栈或递归
let colors = this.initializeColor();
this.dfsVisit(initV, colors, handler);
}
Graph.prototype.dfsVisit = function (v, colors, handler) {
colors[v] = 'gray';
handler(v);
let vlist = this.edges.get(v);
for (let i = 0; i < vlist.length; i++) {
let temp = vlist[i];
if(colors[temp] == 'white'){
this.dfsVisit(temp, colors, handler);
}
}
colors[v] = 'black';
}
}
let g = new Graph()
let myVertex = ['A','B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'];
for (let i = 0; i < myVertex.length; i++) {
g.addVertex(myVertex[i]);
}
g.addEdge('A', 'B');
g.addEdge('A', 'C');
g.addEdge('A', 'D');
g.addEdge('C', 'D');
g.addEdge('C', 'G');
g.addEdge('D', 'G');
g.addEdge('D', 'H');
g.addEdge('B', 'E');
g.addEdge('B', 'F');
g.addEdge('E', 'I');
// alert(g);
// console.log(g.toString());
let result = '';
g.DFS(g.vertexes[0], function (v) {
result += v + ' ';
})
alert(result);