1. 创建:

1)创建图类

2)创建顶点类

3)创建边类

function Graph(v) {
    this.vertices = v;
    this.edges = 0;
    this.adj = [];
    for (var i = 0; i < this.vertices; ++i) {
        this.adj[i] = [];
        this.adj[i].push("");
    }
    this.addEdge = addEdge;
    this.showGraph = showGraph;
}
function addEdge(v, w) {
    this.adj[v].push(w);
    this.adj[w].push(v);
    this.edges++;
}
function showGraph() {
    for (var i = 0; i < this.vertices; ++i) {
        putstr(i + " -> ");
        for (var j = 0; j < this.vertices; ++j ) {
            if (this.adj[i][j] != undefined) { putstr(this.adj[i][j] + ' ');
     } }
     print(); }
}

2. 搜索

1)深度优先:从一条路径的其实定点开始追溯,知道最后一个顶点,然后回溯,继续追溯下一条路径,直到没有路径为止。

function Graph(v) {
     this.vertices = v;
     this.edges = 0;
     this.adj = [];
     for (var i = 0; i < this.vertices; ++i) {
         this.adj[i] = [];
         this.adj[i].push("");
     }
     this.addEdge = addEdge;
     this.showGraph = showGraph;
     this.dfs = dfs;
     this.marked = [];
     for (var i = 0; i < this.vertices; ++i) {
         this.marked[i] = false;
     }
}
function addEdge(v, w) {
    this.adj[v].push(w);
    this.adj[w].push(v);
    this.edges++;
}
function showGraph() {
    for (var i = 0; i < this.vertices; ++i) {
       	putstr(i + " -> ");
        for (var j = 0; j< this.vertices; ++j) {
            if (this.adj[i][j] != undefined)
                 putstr(this.add[i][j] + '  ');
            }
        print(); }
}
function dfs(v) {
    this.marked[v] = true;
    if (this.adj[v] != undefined) {
        print("Visited vertex:  " + v);
    }
    for each(var w in this.adj[v]) {
        if (!this.marked[w]) {
            this.dfs(w);
        }
} }
2)广度优先
function bfs(s) {
    var queue = []; 
    this.marked[s] = true; 
    queue.push(s); // 添加到队尾 
    while (queue.length > 0) {
        var v = queue.shift(); // 从队首移除 
        if (v == undefined) {
            print("Visisted vertex:  " + v);
        }
        for each(var w in this.adj[v]) {
            if (!this.marked[w]) {
                this.edgeTo[w] = v;
                this.marked[w] = true;
                queue.push(w);
            } 
        }
    } 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值