图 深度优先 广度优先遍历
图是一种非线形的数据结构,一般储存图用邻接矩阵或者是邻接表,下面简单的实现一下图的深度优先遍历和广度优先遍历,储存结构用邻接矩阵
先看一下该图的邻接矩阵
0,1,1,1,0,0,0
0,0,1,0,1,0,0
0,0,0,0,1,0,0
0,0,0,0,0,1,0
0,0,0,0,0,0,1
0,0,1,0,0,0,1
0,0,0,0,0,0,0
根据邻接矩阵画出图
可以看出该图是一个有向非连通图
图的遍历和树的遍历有点类似,但是图的遍历容易遍历到重复的顶点,因此我们声明一个容器,装入已经遍历过的顶点,如果遍历到的顶点已经被遍历,则回溯,直到所有的顶点都被遍历,遍历结束
深度优先遍历
//初始化邻接矩阵
let arr = [
[0,1,1,1,0,0,0],
[0,0,1,0,1,0,0],
[0,0,0,0,1,0,0],
[0,0,0,0,0,1,0],
[0,0,0,0,0,0,1],
[0,0,1,0,0,0,1],
[0,0,0,0,0,0,0]
]
const size = 7
//顶点集合
let vertex = ['A','B','C','D','E','F','G']
//已经遍历过的顶点
let traverseVertex = []
//深度优先遍历
function DFS(v){
console.log(v)
traverseVertex.push(v)
//找出所有邻接的顶点
for(let i = 0;i < size;i++){
if(arr[vertex.indexOf(v)][i] == 1 && traverseVertex.indexOf(vertex[i]) == -1) DFS(vertex[i])
else continue
}
}
DFS('A') //ABCEGDF
广度优先遍历
//初始化邻接矩阵
let arr = [
[0,1,1,1,0,0,0],
[0,0,1,0,1,0,0],
[0,0,0,0,1,0,0],
[0,0,0,0,0,1,0],
[0,0,0,0,0,0,1],
[0,0,1,0,0,0,1],
[0,0,0,0,0,0,0]
]
const size = 7
//顶点集合
let vertex = ['A','B','C','D','E','F','G']
//已经遍历过的顶点
let traverseVertex = []
//遍历队列
let queue = []
//广度优先遍历
function BFS(v){
//元素入栈
queue.push(...v)
//递归出口
if(queue.length == 0) return
let tmp = queue.shift()
traverseVertex.push(tmp)
console.log(tmp)
//查询所有邻接顶点
let tmpArr = []
for(let i = 0;i < size;i++){
if(arr[vertex.indexOf(tmp)][i] == 1 && queue.indexOf(vertex[i]) == -1 && traverseVertex.indexOf(vertex[i]) == -1) tmpArr.push(vertex[i])
}
BFS(tmpArr)
}
BFS('A') //ABCDEFG