当前位置:首页 > JavaScript

js实现图

2026-01-14 14:22:06JavaScript

JavaScript 实现图的常用方法

在 JavaScript 中,图(Graph)可以通过多种方式实现,常见的包括邻接表(Adjacency List)和邻接矩阵(Adjacency Matrix)。以下是具体实现方法:

邻接表实现

邻接表是图的常见表示方法,适合稀疏图(边数远小于顶点数的平方)。使用对象或数组存储顶点及其相邻顶点。

class Graph {
  constructor() {
    this.adjacencyList = {};
  }

  addVertex(vertex) {
    if (!this.adjacencyList[vertex]) {
      this.adjacencyList[vertex] = [];
    }
  }

  addEdge(vertex1, vertex2) {
    if (!this.adjacencyList[vertex1] || !this.adjacencyList[vertex2]) {
      return false;
    }
    this.adjacencyList[vertex1].push(vertex2);
    this.adjacencyList[vertex2].push(vertex1); // 无向图需双向添加
  }

  removeEdge(vertex1, vertex2) {
    this.adjacencyList[vertex1] = this.adjacencyList[vertex1].filter(
      v => v !== vertex2
    );
    this.adjacencyList[vertex2] = this.adjacencyList[vertex2].filter(
      v => v !== vertex1
    );
  }

  removeVertex(vertex) {
    while (this.adjacencyList[vertex].length) {
      const adjacentVertex = this.adjacencyList[vertex].pop();
      this.removeEdge(vertex, adjacentVertex);
    }
    delete this.adjacencyList[vertex];
  }
}

邻接矩阵实现

邻接矩阵适合稠密图(边数接近顶点数的平方),使用二维数组表示顶点间的连接关系。

js实现图

class Graph {
  constructor(numVertices) {
    this.matrix = Array(numVertices)
      .fill()
      .map(() => Array(numVertices).fill(0));
  }

  addEdge(i, j) {
    this.matrix[i][j] = 1;
    this.matrix[j][i] = 1; // 无向图需对称设置
  }

  removeEdge(i, j) {
    this.matrix[i][j] = 0;
    this.matrix[j][i] = 0;
  }

  hasEdge(i, j) {
    return this.matrix[i][j] === 1;
  }
}

图的遍历算法

深度优先搜索(DFS)

递归或栈实现,适合查找路径或连通分量。

depthFirstSearch(start) {
  const result = [];
  const visited = {};
  const adjacencyList = this.adjacencyList;

  (function dfs(vertex) {
    if (!vertex) return null;
    visited[vertex] = true;
    result.push(vertex);
    adjacencyList[vertex].forEach(neighbor => {
      if (!visited[neighbor]) {
        return dfs(neighbor);
      }
    });
  })(start);

  return result;
}

广度优先搜索(BFS)

队列实现,适合查找最短路径或层级遍历。

js实现图

breadthFirstSearch(start) {
  const queue = [start];
  const result = [];
  const visited = { [start]: true };

  while (queue.length) {
    const vertex = queue.shift();
    result.push(vertex);
    this.adjacencyList[vertex].forEach(neighbor => {
      if (!visited[neighbor]) {
        visited[neighbor] = true;
        queue.push(neighbor);
      }
    });
  }
  return result;
}

加权图的实现

对于带权重的图(如 Dijkstra 算法场景),邻接表可扩展为存储对象而非单纯顶点。

addWeightedEdge(vertex1, vertex2, weight) {
  this.adjacencyList[vertex1].push({ node: vertex2, weight });
  this.adjacencyList[vertex2].push({ node: vertex1, weight }); // 无向图
}

实际应用示例

以下是通过图解决简单路径问题的示例:

const graph = new Graph();
graph.addVertex("A");
graph.addVertex("B");
graph.addVertex("C");
graph.addEdge("A", "B");
graph.addEdge("B", "C");
console.log(graph.depthFirstSearch("A")); // ["A", "B", "C"]

通过以上方法,可以灵活实现图的存储、修改和遍历操作。邻接表在大多数场景下更节省空间,而邻接矩阵适合快速查询边是否存在。

标签: js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

js 实现跳转

js 实现跳转

使用 window.location.href 进行跳转 通过修改 window.location.href 可以跳转到指定 URL,浏览器会加载新页面: window.location.hre…

js图片上传实现

js图片上传实现

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API实现基础图片上传功能。HTML部分需要设置accept="image/…