LoginSignup
0
0

More than 1 year has passed since last update.

 隣接リストをJavaで実装しようとすると、案外手間だった。
 訂正すると滅茶苦茶手間だった。Javaは可変長配列の扱いが難しい……。

 まともな資料もないし……もしかしてJavaで組むこと自体が想定されてないモデルだったりするのだろうか。

コード

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);

        int n = sc.nextInt();
        int m = sc.nextInt();

        ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();   //ArrayListを二次元に

        for(int i=0; i<n; i++){
            ArrayList<Integer> ar = new ArrayList<Integer>();   //外側のListに添え字を作るために
            al.add(ar);   //N回、入れ物のArrayListを作っておく
        }

        for(int i=0; i<m; i++){
            int a = sc.nextInt()-1;
            int b = sc.nextInt()-1;

            al.get(a).add(b);   //外側Listの添え字をgetして、中のListにbをaddする
            al.get(b).add(a);   //同様のことをする。隣接リストなので数字を入れ替える
        }

        for(int i=0; i<n; i++){
            Collections.sort(al.get(i));   //外側リストの添え字ごとに中身をソートして
            for(int j=0; j<al.get(i).size(); j++){
                System.out.print(al.get(i).get(j));   //表示
            }
            System.out.println("");
        }
    }
}

参考

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