노드와 에지로 구성된 집합.
(트리도 그래프의 일종)
(노드 개수 N)
에지 중심 알고리즘인 벨만 포드, 크루스칼(MST)에 사용 가능
A[2][N]
A[3][N]
노드가 적을 때 사용 가능
A[N][N]
(A[1][2] = 1 or 0)A[N][N]
(A[1][2] = 4)ArrayList<ArrayList<Integer>>
ArrayList<ArrayList<Node>>
for (int i = 0; i < V + 1; i++) { graph.add(new ArrayList<Node>()); }
graph.get(x).add(new Node(y, w));
graph.get(x)
graph.get(x).get(i)
(ArrayList<Integer>[] adjacencyList = new ArrayList[node+1];
는 타입 안정성이 떨어짐)
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt();
int E = sc.nextInt();
// 인접 리스트
ArrayList<ArrayList<Node>> graph = new ArrayList<ArrayList<Node>>();
// 초기화
for (int i = 0; i < V + 1; i++) {
graph.add(new ArrayList<Node>());
}
int x, y, w;
for (int i = 0; i < E; i++) {
x = sc.nextInt();
y = sc.nextInt();
w = sc.nextInt();
// 단방향
graph.get(x).add(new Node(y, w));
}
System.out.println(graph);
}
public static class Node {
int end;
int weight;
public Node(int end, int weight) {
this.end = end;
this.weight = weight;
}
@Override
public String toString() {
return "[" + end + ", " + weight + "]";
}
}
}
(구현이 복잡하지만 시간복잡도와 공간 효율 좋음, 노드 중심 알고리즘에 유용.)
(DFS, BFS는 가중치 없는 그래프 탐색)