# 【你该懂一点Javascript算法系列】之【图类】的定义及深度优先与广度优先搜索算法

github直达地址 https://github.com/fanshyiis/...

“检查相邻性” 是指对于给定的顶点，尝试确定它是否是另一个顶点的邻居。在邻接列表中检查相邻性的时间复杂度是O(V)，因为最坏的情况是一个顶点与每一个顶点都相连。

``````class Dictionary {
constructor () {
this.items = {}
}

has (key) {
return key in this.items
}

set (key, val) {
this.items[key] = val
}

delete (key) {
if (this.has(key)) {
delete this.items[key]
return true
} else {
return false
}
}

get (key) {
return this.has(key)? this.items[key] : undefined
}

values () {
let values = []
for (let k in this.items) {
if (this.has(k)) {
values.push(this.items[k])
}
}
return values
}
}

class Queue {
constructor () {
this.items = []
}

enqueue (element) {
this.items.push(element)
}

dequeue () {
return this.items.shift()
}

isEmpty() {
return this.items.length === 0
}
}``````
Dictionary 字典类来辅助存贮键值对
Queue 队列类来存贮队列
``````//定义class Graph
class Graph {
constructor () {
this.vertices = []
this.adjList = new Dictionary()
}
}``````

vertices 存储点信息
adjList 存储顶点间的链接关系
``````  addVertex (v) {
this.vertices.push(v)
this.adjList.set(v, [])
}

addEdge (v, w) {
this.adjList.get(v).push(w)
}``````
addVertex 添加顶点的方法，存贮在数组vertices，并且初始化adjList字典里的值
addEdge 添加单向边 接收两个值 在邻接字典里加上从第一个顶点到第二个的关系

``````et graph = new Graph()
let mv = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
mv.map(val => {
graph.addVertex(val)
})
graph.addEdge('A', 'B')
graph.addEdge('A', 'C')
graph.addEdge('A', 'D')
graph.addEdge('C', 'D')
graph.addEdge('C', 'G')
graph.addEdge('D', 'G')
graph.addEdge('D', 'H')
graph.addEdge('B', 'E')
graph.addEdge('B', 'F')
graph.addEdge('E', 'I')``````

``````  toString () {
let s = ''
for (let i = 0; i < this.vertices.length; i++) {
s += this.vertices[i] + '->'
let neighbors = this.adjList.get(this.vertices[i])
for (let j = 0; j < neighbors.length; j++) {
s += neighbors[j] + ' '
}
s += '\n'
}
return s
}``````

``````A->B C D
B->E F
C->D G
D->G H
E->I
F->
G->``````

``````  BFS (v, callback) {
let color = this.initializeColor(),
queue = new Queue()
queue.enqueue(v)

while (!queue.isEmpty()) {
let u = queue.dequeue(),
neighbors = this.adjList.get(u)
color[u] = 'grey'
neighbors.map(val => {
if (color[val] === 'white') {
color[val] = 'grey'
queue.enqueue(val)
}
})
color[u] = 'black'
if (callback) {
callback(u)
}
}
}``````

1.初始化各个顶点的颜色（白色 - 未访问； 灰色 - 已发现； 黑色 - 已经探索完）
2.初始化一个队列
3.首先队列入顶点 v
4.如果队列不会空，则取队列第一个进行探索
5.探索过程中获取当前顶点的所有邻接顶点，并推进队列
6.完成5后，标记当前为黑色

A 探索 队列入 B - C - D

。。。

``````  DFS (callback) {
let color = this.initializeColor()
this.vertices.map(val => {
if (color[val] === 'white') {
this.dfsVisit(val, color, callback)
}
})
}

dfsVisit (u, color, callback) {
color[u] = 'grey'
if (callback) {
callback(u)
}
let neighbors = this.adjList.get(u)
neighbors.map(val => {
if (color[val] === 'white') {
this.dfsVisit(val, color, callback)
}
})
color[u] = 'black'
}``````

1.初始化各个顶点的颜色（白色 - 未访问； 灰色 - 已发现； 黑色 - 已经探索完）
2.对顶点进行遍历并进行dfsVisit函数探索
3.优先进行最新探索的边进行深度探索，完成后标记探索完成

。。。

``````/*
* @Author: koala_cpx
* @Date:   2019-01-24 10:48:01
* @Last Modified by:   koala_cpx
* @Last Modified time: 2019-01-24 10:56:33
*/
class Dictionary {
constructor () {
this.items = {}
}

has (key) {
return key in this.items
}

set (key, val) {
this.items[key] = val
}

delete (key) {
if (this.has(key)) {
delete this.items[key]
return true
} else {
return false
}
}

get (key) {
return this.has(key)? this.items[key] : undefined
}

values () {
let values = []
for (let k in this.items) {
if (this.has(k)) {
values.push(this.items[k])
}
}
return values
}
}

class Queue {
constructor () {
this.items = []
}

enqueue (element) {
this.items.push(element)
}

dequeue () {
return this.items.shift()
}

isEmpty() {
return this.items.length === 0
}
}

class Graph {
constructor () {
this.vertices = []
this.adjList = new Dictionary()
this.time = 0
}

addVertex (v) {
this.vertices.push(v)
this.adjList.set(v, [])
}

addEdge (v, w) {
this.adjList.get(v).push(w)
// this.adjList.get(w).push(v)
}

BFS (v, callback) {
let color = this.initializeColor(),
queue = new Queue()
queue.enqueue(v)

while (!queue.isEmpty()) {
let u = queue.dequeue(),
neighbors = this.adjList.get(u)
color[u] = 'grey'
neighbors.map(val => {
if (color[val] === 'white') {
color[val] = 'grey'
queue.enqueue(val)
}
})
color[u] = 'black'
if (callback) {
callback(u)
}
}
}

BFSPlus (v) {
let color = this.initializeColor(),
queue = new Queue(),
d = [],
pred = []

queue.enqueue(v)
this.vertices.map(val => {
d[val] = 0
pred[val] = null
})

while (!queue.isEmpty()) {
let u = queue.dequeue(),
neighbors = this.adjList.get(u)

color[u] = 'grey'
neighbors.map(val => {
if (color[val] === 'white') {
color[val] = 'grey'
d[val] = d[u] + 1
pred[val] = u
queue.enqueue(val)
}
})
color[u] = 'black'
}

return {
distances: d,
predecessors: pred
}
}

DFS (callback) {
let color = this.initializeColor()
this.vertices.map(val => {
if (color[val] === 'white') {
this.dfsVisit(val, color, callback)
}
})
}

DFSPlus () {
let color = this.initializeColor(),
d = [],
f = [],
p = []

this.time = 0
this.vertices.map(val => {
f[val] = 0
d[val] = 0
p[val] = null
})

this.vertices.map(val => {
if (color[val] === 'white') {
this.dfsPlusVisit(val, color, d, f, p)
}
})

return {
discovery: d,
finished: f,
predecessors: p
}
}

dfsPlusVisit (u, color, d, f, p) {
console.log('discovery' + u)
color[u] = 'grey'
d[u] = ++this.time
let neighbors = this.adjList.get(u)
neighbors.map(val => {
if (color[val] === 'white') {
p[val] = u
this.dfsPlusVisit(val, color, d, f, p)
}
})
color[u] = 'black'
f[u] = ++this.time
console.log('explored' + u)
}

dfsVisit (u, color, callback) {
color[u] = 'grey'
if (callback) {
callback(u)
}
let neighbors = this.adjList.get(u)
neighbors.map(val => {
if (color[val] === 'white') {
this.dfsVisit(val, color, callback)
}
})
color[u] = 'black'
}

outPut(obj) {
let fromVertex = this.vertices[0],
{ predecessors } = obj
this.vertices.map(val => {
let path = new Array()
for (var v = val; v !== fromVertex; v = predecessors[v]) {
path.push(v)
}
path.push(fromVertex)
let s = path.pop()
while (path.length !== 0) {
s += ' -- ' + path.pop()
}
console.log(s)
})
}

initializeColor () {
let color = []
this.vertices.map(val => {
color[val] = 'white'
})
return color
}

toString () {
let s = ''
for (let i = 0; i < this.vertices.length; i++) {
s += this.vertices[i] + '->'
let neighbors = this.adjList.get(this.vertices[i])
for (let j = 0; j < neighbors.length; j++) {
s += neighbors[j] + ' '
}
s += '\n'
}
return s
}
}

let a = new Dictionary()
a.set('ss', 1111)
a.set('s1', 1111)
a.set('s2', 1112)
a.set('s3', 1114)

a.delete('s2')
console.log(a.has('s3'))

console.log(a.values())

let graph = new Graph()
let mv = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']
mv.map(val => {
graph.addVertex(val)
})
graph.addEdge('A', 'B')
graph.addEdge('A', 'C')
graph.addEdge('A', 'D')
graph.addEdge('C', 'D')
graph.addEdge('C', 'G')
graph.addEdge('D', 'G')
graph.addEdge('D', 'H')
graph.addEdge('B', 'E')
graph.addEdge('B', 'F')
graph.addEdge('E', 'I')

console.log(graph.toString())

function print(val) {
console.log('vis' + val)
}

graph.BFS('A', print)
console.log(graph.BFSPlus("A"))
graph.outPut(graph.BFSPlus("A"))
graph.DFS(print)
console.log(graph.DFSPlus())

let graph2 = new Graph()
let mv2 = ['A', 'B', 'C', 'D', 'E', 'F']
mv2.map(val => {
graph2.addVertex(val)
})
graph2.addEdge('A', 'C')
graph2.addEdge('A', 'D')
graph2.addEdge('B', 'D')
graph2.addEdge('B', 'E')
graph2.addEdge('C', 'F')
graph2.addEdge('F', 'E')

let r = graph2.DFSPlus()
console.log(r)

``````

github直达地址 https://github.com/fanshyiis/...