邻接矩阵的JS实现
来源:2-3 图的基本表示:邻接矩阵

qq_crusader_1
2022-05-10
还是采用外部g.txt存值,js代码的实现如下:
const fs = require('fs'); const path = require('path'); function AdjMatrix(filename) { var V, E, adj = [], index = 0; var file = fs.readFileSync(filename, 'utf8'); var vertices = file.split(/\s\n?/g) V = +vertices[index++]; adj = Array.from(new Array(V), () => new Array(V).fill(0)); E = vertices[index++]; for (var i = 0; i < E; i++) { let a = +vertices[index++]; let b = +vertices[index++]; adj[a][b] = 1; adj[b][a] = 1; } console.log('adj', adj) return adj; } var adjMatrix = new AdjMatrix(`${__dirname}/g.txt`)
写回答
1回答
-
感谢分享,继续加油!:)00
相似问题