前言
有向和无向图实现方式
图的实现
type NodeType = string | number;interface GNode { key: NodeType; value: NodeType;}interface Edge { a: NodeType; b: NodeType; weight: number;}class Graph { nodes: GNode[] = []; edges: Map<string, Edge> = new Map(); directed: boolean = true; constructor(directed: boolean = true) { this.directed = directed; } addNode(key: NodeType, value: NodeType = key) { this.nodes.push({ key, value }); } removeNode(key: NodeType) { this.nodes = this.nodes.filter((node: GNode) => node.key !== key); [...this.edges.values()].forEach(({ a, b }) => { if (a === key || b === key) this.edges.delete(JSON.stringify([a, b])); }); } addEdge(a: NodeType, b: NodeType, weight: number) { this.edges.set(JSON.stringify([a, b]), { a, b, weight }); if (!this.directed) this.edges.set(JSON.stringify([b, a]), { a: b, b: a, weight }); } removeEdge(a: NodeType, b: NodeType) { this.edges.delete(JSON.stringify([a, b])); if (!this.directed) this.edges.delete(JSON.stringify([b, a])); } findNode(key: NodeType) { return this.nodes.find((node: GNode) => node.key === key); } hasEdge(a: NodeType, b: NodeType) { return this.edges.has(JSON.stringify([a, b])); } getEdgeWeight(a: NodeType, b: NodeType) { return this.edges.get(JSON.stringify([a, b]))?.weight; } setEdgeWeight(a: NodeType, b: NodeType, weight: number) { return this.addEdge(a, b, weight); } // 获取 key 节点指向的所有节点 adjacent(key: NodeType): NodeType[] { return [...this.edges.values()].reduce((acc, { a, b }) => { if (key === a) acc.push(b); return acc; }, []); } indegree(key: NodeType): number { return [...this.edges.values()].reduce((count, { a, b }) => { if (key === b) count++; return count; }, 0); } outdegree(key: NodeType): number { return [...this.edges.values()].reduce((count, { a, b }) => { if (key === a) count++; return count; }, 0); }}