【从前端视角看图结构】用邻接表和邻接矩阵处理“页面跳转图”!

6 阅读2分钟

🧠 引言

想象一下你的前端项目:

  • 首页跳转到商品页
  • 商品页跳转到支付页
  • 商品页还能跳到评论页…

这是不是就像一个“页面跳转图”?
其实这正是“图(Graph)”的经典应用场景。

本篇文章将从“前端页面跳转”出发,带你用邻接表和邻接矩阵实现一个有向图结构,并用 JS/Python 分别编码,让你轻松理解图的核心概念与实现方式。


🔍 一、什么是图?

图(Graph)是由节点(点)和连接它们的边构成的数据结构。

图的分类:

类型是否有方向是否有权值
无向图可有/无
有向图可有/无
有权图✅或否

📄 二、图的两种常见存储方式

✅ 邻接表(Adjacency List)

用哈希表存每个点的“连接列表”。

{
  A: [B, C],
  B: [C],
  C: []
}

✅ 邻接矩阵(Adjacency Matrix)

用二维数组表示所有点的连接关系。

   A B C
A [0 1 1]
B [0 0 1]
C [0 0 0]

💻 三、JS 实现邻接表图结构

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

  addVertex(v) {
    if (!this.adjList[v]) this.adjList[v] = [];
  }

  addEdge(from, to) {
    this.addVertex(from);
    this.addVertex(to);
    this.adjList[from].push(to);
  }

  print() {
    for (const key in this.adjList) {
      console.log(`${key} ➡️ ${this.adjList[key].join(', ')}`);
    }
  }
}

// 示例:页面跳转图
const g = new Graph();
g.addEdge('Home', 'Product');
g.addEdge('Product', 'Payment');
g.addEdge('Product', 'Review');
g.print();

📌 输出:

Home ➡️ Product  
Product ➡️ Payment, Review  
Review ➡️  
Payment ➡️  

🐍 四、Python 实现邻接表图结构

class Graph:
    def __init__(self):
        self.adj_list = {}

    def add_vertex(self, v):
        if v not in self.adj_list:
            self.adj_list[v] = []

    def add_edge(self, from_v, to_v):
        self.add_vertex(from_v)
        self.add_vertex(to_v)
        self.adj_list[from_v].append(to_v)

    def print(self):
        for key in self.adj_list:
            print(f"{key} ➡️ {', '.join(self.adj_list[key])}")

# 示例
g = Graph()
g.add_edge("Home", "Product")
g.add_edge("Product", "Payment")
g.add_edge("Product", "Review")
g.print()

🧠 五、邻接矩阵实现(高级一点)

✅ JS 示例(稀疏图建议用邻接表)

class MatrixGraph {
  constructor(vertices) {
    this.vertices = vertices;
    this.matrix = Array.from({ length: vertices.length }, () => Array(vertices.length).fill(0));
  }

  addEdge(from, to) {
    const i = this.vertices.indexOf(from);
    const j = this.vertices.indexOf(to);
    this.matrix[i][j] = 1;
  }

  print() {
    console.log('  ' + this.vertices.join(' '));
    this.matrix.forEach((row, i) => {
      console.log(this.vertices[i] + ' ' + row.join('  '));
    });
  }
}

const g = new MatrixGraph(['Home', 'Product', 'Payment', 'Review']);
g.addEdge('Home', 'Product');
g.addEdge('Product', 'Payment');
g.addEdge('Product', 'Review');
g.print();

⚠️ 六、常见图结构易错点

错误场景正确做法
添加边前未建点addVertex() 检查确保存在顶点
邻接矩阵坐标错乱确保 indexOf 返回的是正确下标
忘了处理环或重复边加边前可以检查是否已存在(进阶)

🔄 七、拓展任务

  • 实现图的 DFS(深度优先搜索)
  • 实现图的 BFS(广度优先搜索)
  • 用图结构模拟网站站内推荐系统

🧩 总结一句话

图结构是“关系型问题”的最强武器,掌握邻接表和矩阵存储方式,你就能游刃有余地处理各种复杂连接问题!


下一篇预告:

📘 第8篇:【JS 与 Python 实现栈与队列】深入理解它们与浏览器、任务调度的联系!