보통의 경우, 간선은 1이라고 생각하지만, 가중치를 가진 계산을 할 수 있다.
→ 정해주지 않는 경우, 문맥을 통한 파악이 필요하다.
(ex. 일방 통행하는 노선을 계획하는 경우 : 유향 )
: 하나의 사이클이 완성되는 경우, 순환 그래프라고 할 수 있다.
0→2, 2→4, 4→6
0-2-4-6
/ 0-1-6
1. 인접행렬
자바 코드
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt(); // 정점의 갯수(0 또는 1로 시작)
int E = sc.nextInt(); // 간선의 갯수
int[][] adjArr = new int[V][V]; // 만약 시작점이 1이라면, 각 V+1을 해줘야 한다.
// E개의 간선을 입력 받을 반복문
for(int i = 0; i < E; i++) {
int A = sc.nextInt();
int B = sc.nextInt(); // 두 개의 정점을 갖기 때문에
int W = sc.nextInt(); // 가중치가 있다면 값은 3개
adjArr[A][B] = W; // 가중치가 없다면 1을 저장해주면 된다.
adjArr[A][B] = W; // 만약 무향이라면 반대의 경우도 같이 작성해줘야 한다.
}
}
2. 인접 리스트
자바 구현
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt(); // 정점의 갯수(0 또는 1로 시작)
int E = sc.nextInt(); // 간선의 갯수
List<Integer>[] adjList = new ArrayList[V];
// 기본적으로 전부 생성을 해주어야 nullpointexception이 안 뜬다.
for(int i = 0; i < V; i++) {
adjList[i] = new ArrayList<>();
}
for(int i = 0; i < E; i++) {
int A = sc.nextInt();
int B = sc.nextInt();
// 가중치를 같이 저장하고 싶다면,
// 1. 클래스를 정의하거나
// 2. int[] 를 이용해서 넣어야 한다.
adjList[A].add(B);
adjList[B].add(A);
}
}
3. 간선 배열
자바 구현
public class 그래프_03_간선배열 {
static class Edge{
int A, B, W; // 시작, 끝, 가중치
Edge(int A, int B, int W){
this.A = A;
this.B = B;
this.W = W;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int V = sc.nextInt(); // 정점의 갯수(0 또는 1로 시작)
int E = sc.nextInt(); // 간선의 갯수
Edge[] edges = new Edge[2]; // 객체 배열 생성
for(int i = 0; i < E; i++) {
int A = sc.nextInt();
int B = sc.nextInt();
int W = sc.nextInt();
edges[i] = new Edge(A, B, W);
}
// 혹은 방법 2 ------------------------
List<Edge> edges2 = new ArrayList<>();
for(int i = 0; i < E; i++) {
edges2.add(new Edge(sc.nextInt(), sc.nextInt(), sc.nextInt()));
}
}
}
클래스를 정의하지 않고 int[][] edges3 = new int[E][3];
과 같이 선언하여 배열을 저장할 수도 있다.
// 혹은 방법 2 ------------------------
List<Edge> edges2 = new ArrayList<>();
for(int i = 0; i < E; i++) {
edges2.add(new Edge(sc.nextInt(), sc.nextInt(), sc.nextInt()));
}
int[][] edges3 = new int[E][3];
for(int i = 0; i < E; i++) {
int A = sc.nextInt();
int B = sc.nextInt();
int W = sc.nextInt();
edges3[i][0] = A;
edges3[i][1] = B;
edges3[i][2] = W;
}