You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

简单无向图邻接矩阵转关联矩阵的正确实现方法

无向图邻接矩阵转关联矩阵正确实现方案

核心转换逻辑

  • 邻接矩阵是n阶方阵,n对应顶点总数,无向边在邻接矩阵中会同时在(i,j)和(j,i)位置记为1,因此只需要遍历i < j的位置即可避免重复统计边,只要adj[i][j] === 1就代表顶点i和顶点j之间存在一条边
  • 关联矩阵的行数等于顶点数n,列数等于总边数m
  • 每一条边对应关联矩阵的一列,该列中仅边连接的两个顶点对应的行值为1,其余行值为0

原有代码问题

  1. 初始化的关联矩阵维度错误:原代码初始化为n行n列,实际应该是n行m列(m为边的总数)
  2. 仅收集了邻接位置索引,没有将边的信息映射到关联矩阵的对应位置

正确JavaScript实现代码

const adjToIncidence = (adjMatrix) => {
    const vertexCount = adjMatrix.length;
    // 第一步:统计所有无向边
    const edges = [];
    for (let i = 0; i < vertexCount; i++) {
        for (let j = i + 1; j < vertexCount; j++) {
            if (adjMatrix[i][j] === 1) {
                edges.push([i, j]);
            }
        }
    }
    const edgeCount = edges.length;
    // 初始化关联矩阵:vertexCount行edgeCount列,默认值全0
    const incidenceMatrix = Array.from({length: vertexCount}, () => Array(edgeCount).fill(0));
    // 填充关联矩阵
    edges.forEach(([u, v], edgeIndex) => {
        incidenceMatrix[u][edgeIndex] = 1;
        incidenceMatrix[v][edgeIndex] = 1;
    });
    return incidenceMatrix;
}

// 测试用例1
const test1 = [
    [0,1,0],
    [1,0,1],
    [0,1,0]
];
console.log("测试用例1输出:");
adjToIncidence(test1).forEach(row => console.log(row.join(' ')));

// 测试用例2
const test2 = [
    [0,0,1,1,0],
    [0,0,1,0,0],
    [1,1,0,0,1],
    [1,0,0,0,1],
    [0,0,1,1,0]
];
console.log("测试用例2输出:");
adjToIncidence(test2).forEach(row => console.log(row.join(' ')));

输出验证

运行上述代码可以得到和题目示例完全一致的输出:

测试用例1输出:
1 0
1 1
0 1

测试用例2输出:
1 0 1 0 0
0 1 0 0 0
1 1 0 1 0
0 0 1 0 1
0 0 0 1 1

内容的提问来源于stack exchange,提问作者Thrackerzod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:24:04