2026-02-11 13:15:37
在JavaScript中,图形数据结构通常用于表示和处理由顶点(Vertices)和边(Edges)组成的图。这种数据结构在可视化、路径查找、网络分析等领域有广泛应用。以下是关于JavaScript中图形数据结构的详细说明:
1. 图形数据结构的基本概念邻接表:每个顶点存储一个列表,记录与其直接相连的顶点。
邻接矩阵:用二维数组表示顶点间的连接关系(1表示连接,0表示无连接)。
邻接表适合稀疏图(边较少的情况),通过对象或Map存储顶点及其邻居。
// 定义图结构class Graph { constructor() { this.adjacencyList = new Map(); // 使用Map存储顶点和邻居 } // 添加顶点 addVertex(vertex) { if (!this.adjacencyList.has(vertex)) { this.adjacencyList.set(vertex, []); } } // 添加边(无向图) addEdge(vertex1, vertex2) { this.adjacencyList.get(vertex1).push(vertex2); this.adjacencyList.get(vertex2).push(vertex1); } // 打印邻接表 printGraph() { for (let [vertex, neighbors] of this.adjacencyList) { console.log(`${vertex} -> ${neighbors.join(', ')}`); } }}// 示例用法const graph = new Graph();graph.addVertex('公司A');graph.addVertex('公司B');graph.addEdge('公司A', '公司B');graph.printGraph();// 输出:公司A -> 公司B// 公司B -> 公司A(2) 邻接矩阵实现邻接矩阵适合稠密图(边较多的情况),用二维数组表示连接关系。
class GraphMatrix { constructor() { this.vertices = []; // 存储顶点 this.matrix = []; // 邻接矩阵 } // 添加顶点 addVertex(vertex) { this.vertices.push(vertex); const n = this.vertices.length; // 初始化新行和列 for (let i = 0; i < n; i++) { this.matrix[i] = this.matrix[i] || []; this.matrix[i][n - 1] = 0; // 新列初始化为0 this.matrix[n - 1] = this.matrix[n - 1] || []; this.matrix[n - 1][i] = 0; // 新行初始化为0 } } // 添加边(无向图) addEdge(vertex1, vertex2) { const i = this.vertices.indexOf(vertex1); const j = this.vertices.indexOf(vertex2); this.matrix[i][j] = 1; this.matrix[j][i] = 1; } // 打印矩阵 printMatrix() { console.log(' ' + this.vertices.join(' ')); this.matrix.forEach((row, i) => { console.log(`${this.vertices[i]} ${row.join(' ')}`); }); }}// 示例用法const graphMatrix = new GraphMatrix();graphMatrix.addVertex('公司A');graphMatrix.addVertex('公司B');graphMatrix.addEdge('公司A', '公司B');graphMatrix.printMatrix();// 输出:// 公司A 公司B// 公司A 0 1// 公司B 1 03. 图形可视化在JavaScript中,可以使用SVG或Canvas绘制图形。以下是一个简单的SVG可视化示例:
// 定义顶点和边(参考问题中的数据结构)const nodes = [ { name: "公司名称1", id: 0, x: 50, y: 50 }, { name: "公司名称2", id: 1, x: 200, y: 200 }];const links = [ { startId: 0, endId: 1, x1: 50, y1: 50, x2: 200, y2: 200 }];// 创建SVG元素const svg = document.createElementNS("效果说明:
JavaScript中的图形数据结构可以通过邻接表或邻接矩阵实现,结合SVG/Canvas可实现可视化。核心步骤包括:
通过合理设计数据结构,可以高效处理复杂的图形关系问题。