0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

0
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([]);
}

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

//各行の頂点番号は昇順にソート
g.map(row => row.sort((a, b) => a - b));

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

隣接リストを用意するところ、1行でも書けます。

//隣接リスト
let g = Array(N).fill(0).map(v => v = []);
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?