Created
August 3, 2020 03:44
-
-
Save liuwenzhuang/68322b34bcee7e6c6f58246707847dba to your computer and use it in GitHub Desktop.
typescript realize graph by adjacency list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Graph { | |
public adjList = new Map<any, any[]>(); | |
public numberOfVertexs: number = 0; | |
public addVertex(vertex) { | |
this.adjList.set(vertex, []); | |
this.numberOfVertexs ++; | |
} | |
public addEdge(vertex1, vertex2) { | |
this.adjList.get(vertex1).push(vertex2); | |
this.adjList.get(vertex2).push(vertex1); | |
} | |
public traverseDFS() { | |
if (this.numberOfVertexs === 0) { | |
return []; | |
} | |
const keys = this.adjList.keys(); | |
let key = keys.next().value; // 图没有root节点的概念,此处从第一个加入的节点开始 | |
const output = []; | |
const stack = []; | |
output.push(key); // 已经被遍历的 | |
stack.push(key); // 正在被遍历的 | |
while (stack.length) { | |
const values = this.adjList.get(key); // 节点的关联节点 | |
const notVisitIndex = values.findIndex((value) => output.indexOf(value) === -1); // 关联节点中未被访问的 | |
if (notVisitIndex === -1) { // 如果关联都被访问了,从正在遍历的栈中剔除 | |
stack.pop(); | |
key = stack[stack.length - 1]; | |
continue; | |
} | |
key = values[notVisitIndex]; | |
stack.push(key); | |
output.push(key); | |
} | |
return output; | |
} | |
public traverseBFS() { | |
if (this.numberOfVertexs === 0) { | |
return []; | |
} | |
const keys = this.adjList.keys(); | |
let key = keys.next().value; // 图没有root节点的概念,此处从第一个加入的节点开始 | |
const output = []; | |
const queue = []; | |
queue.push(key); | |
while (queue.length) { | |
const values = this.adjList.get(key); | |
// 筛选未被访问且未放到待被访问队列中的 | |
const unVisitValues = values.filter((value) => output.indexOf(value) === -1 && queue.indexOf(value) === -1); | |
queue.push(...unVisitValues); | |
output.push(queue.shift()); | |
key = queue[0]; | |
} | |
return output; | |
} | |
public print() { | |
const keys = this.adjList.keys(); | |
for (const key of keys) { | |
const values = this.adjList.get(key); | |
const result = values.reduce((acc, cur) => { | |
return `${acc} ${cur}`; | |
}, `${key} =>`); | |
console.log(result); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment