前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >js实现图的构造和遍历

js实现图的构造和遍历

作者头像
theanarkh
发布2019-03-06 09:56:38
1.1K0
发布2019-03-06 09:56:38
举报
文章被收录于专栏:原创分享原创分享
代码语言:javascript
复制
class Graph {
    constructor() {
        this.v = {}; 
        this.vLen = 0;
        this.eLen = 0;
    }

    addEdge(from, to) {
        if (!this.v[from.id]) {
            this.v[from.id] = {};
            this.v[from.id]['node'] = from;
            this.v[from.id]['edge'] = [];
            this.vLen++;
        }
        if (!this.v[to.id]) {
            this.v[to.id] = {};
            this.v[to.id]['node'] = to;
            this.v[to.id]['edge'] = [];
            this.vLen++;
        }
        this.v[from.id]['edge'].push(to);
        this.v[to.id]['edge'].push(from);
        this.eLen++;
    }
}

class Operation {
    constructor(graph) {
        this.graph = graph;
        this.marked = {};
    }
    count(node) {
        if (node !== void 0) {
            if (this.graph['v'][node.id]) {
                return this.graph['v'][node.id]['edge'].length;
            } else {
                return 0;
            }
        } else {
            for (var key in this.graph['v']) {
                console.log(this.graph['v'][key]['edge'].length)
            }
        }
    },

    traversalDFS(node) {

        if (this.marked[node.id]) {
            return;
        }

        console.log(node.id);
        this.marked[node.id] = true;
        var v = this.graph['v'][node.id]['edge'];
        for (var i = 0; i < v.length; i++) {
            if (!this.marked[v[i].id]) {
                this.traversal(v[i])
            }
        }
    },

    traversalBFS(node) {
        var i = 0;
        var queue = [node];
        var point;
        var v;
        var marked = {};
        while(point = queue.shift()) {

            if (marked[point.id]) {
                continue;
            } else {
                console.log(point.id);
                marked[point.id] = true;
            }
            v = this.graph['v'][point.id]['edge'];
            queue = queue.concat(v);
        }
    }
}

var graph = new Graph();
for(var i = 0; i < 5; i++) {
    var from = {id: i};
    var to = {id: i + 1};
    graph.addEdge(from, to);
}
graph.addEdge({id: 2}, {id: 5});
graph.addEdge({id: 1}, {id: 4});

var op = new Operation(graph)

op.traversalDFS(graph, {id:4})
op.traversalBFS(graph, {id:1})
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-02-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 编程杂技 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档