0
0

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 Aランクレベルアップメニュー JavaScript 隣接行列

Posted at

隣接行列 (paizaランク B 相当)

解答例

問題文に沿って実装します。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");
//頂点の数 N と、辺の数 M 
const [N, M] = lines[0].split(" ").map(Number);

//隣接行列
//初期化
let g = [];
for (let i = 0; i < N; i++) {
    g.push(Array(N).fill(0));
}

for (let i = 1; i <= M; i++) {
    //各辺の両端の頂点 a_i , b_i 
    const [a, b] = lines[i].split(" ").map(Number);
    //頂点aと頂点bが辺で結ばれているので
    g[a - 1][b - 1] = 1;
    g[b - 1][a - 1] = 1;
}

//隣接行列出力
console.log(g.map(row => row.join("")).join("\n"));

隣接行列の初期化は以下のように一行でも書けます。

let g = Array(N).fill(0).map(v => v = Array(N).fill(0));
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0