图的广/深du遍历

class Graph {
    constructor(hasDirected = false) {
        this.hasDirected = hasDirected //判断是否为有向图
        this.vertices = [] //顶点
        this.adjList = {} //临接矩阵
    }
    //添加顶点
    addVertex(v) {
        if (!this.vertices.includes(v)) {
            this.vertices.push(v)

            this.adjList[v] = []
        }
    }
    //添加边 v,w为顶点
    addEdge(v, w) {
        !this.adjList[v] ? this.addVertex[v] : null
        !this.adjList[w] ? this.addVertex[w] : null

        this.adjList[v].push(w)

        !this.hasDirected ? this.adjList[w].push(v) : null
    }

    getVertices() {
        return this.vertices
    }

    getAdjList() {
        return this.adjList
    }
}

const graph = new Graph()

const myVertices = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']

for (const e of myVertices) {
    graph.addVertex(e)
}

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);


const Colors = {
    WHITE: 0,
    GREY: 1,
    BLACK: 2
}

function initializeColor(vertices) {
    const color = {}

    for (const e of vertices) {
        color[e] = Colors.WHITE
    }

    return color
}

//breadth
function breadth(graph, statrtVertex, callBack) {
    const vertices = graph.getVertices()
    const adjList = graph.getAdjList()

    const color = initializeColor(vertices)

    const queue = []

    queue.push(statrtVertex)

    while (queue.length > 0) {
        const currentVertex = queue.shift()
        const neighbours = adjList[currentVertex]

        color[currentVertex] = Colors.GREY
        for (const e of neighbours) {

            if (color[e] === Colors.WHITE) {
                color[e] = Colors.GREY
                queue.push(e)
            }

        }

        color[currentVertex] = Colors.BLACK

        callBack ? callBack(currentVertex) : null
    }
}

function printVertex(value) {
    console.log('Visited vertex:', value);
}

breadth(graph, myVertices[0], printVertex)

//depth

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值