图的用法

class Node {
    constructor(value) {
        this.value = value;
        this.inNum = 0;
        this.outNum = 0;
        this.nextNodes = []; // 直接邻居
        this.nextEdges = []; // 直接邻居的边
    }
}

class Edge {
    constructor(weight, fromNode, toNode) {
        this.weight = weight;
        this.fromNode = fromNode;
        this.toNode = toNode;
    }
}

class Graph {
    constructor() {
        this.nodes = new Map();
        this.edges = new Set();
    }
}

const createGraph = (martrix) => {
    const graph = new Graph();
    for (let i = 0; i < martrix.length; i++) {
        const weight = martrix[i][0];
        const from = martrix[i][1];
        const to = martrix[i][2];

        if (!graph.nodes.has(from)) {
            graph.nodes.set(from, new Node(from));
        }
        if (!graph.nodes.has(to)) {
            graph.nodes.set(to, new Node(to));
        }
        const fromNode = graph.nodes.get(from);
        const toNode = graph.nodes.get(to);

        const newEdge = new Edge(weight, fromNode, toNode);

        fromNode.nextNodes.push(toNode);
        fromNode.outNum++;
        toNode.inNum++;

        fromNode.nextEdges.push(newEdge);
        graph.edges.add(newEdge);
    }

    return graph;
};
bfs:
const bfs = (node) => {
    if(node === null) {
        return;
    }
    let queue = [];
    let set = new Set();
    queue.push(node);
    set.add(node);

    while(queue.length > 0) {
        let curNode = queue.shift();
        console.log(curNode.value);
        for(let i = 0; i < curNode.nextNodes.length;i++) {
            if(!set.has(curNode.nextNodes[i])) {
                set.add(curNode.nextNodes[i]);
                queue.push(curNode.nextNodes[i]);
            }
        }
    }
}
dfs:
let onPath = [];
let visited = [];// 记录被遍历过的节点
let track = [];// 记录从起点到当前节点的路径
let hasCycle = false;
const dfs = (node) => {
    if(onPath[node.value]) {
        hasCycle = true;
    }
    if(hasCycle || visited[node.value]) {
        return;
    }
    visited[node.value] = true;
    onPath[node.value] = true;
    track.push(node.value)
    console.log(node.value, track);
    for(var i = 0; i < node.nextNodes.length;i++) {
        dfs(node.nextNodes[i]);
    }
    onPath[node.value] = false;
    track.pop();
}
posted @ 2023-09-08 15:24  拉肥尔  阅读(35)  评论(0)    收藏  举报