item과 item 간의 연결 관계를 표현한다.
import java.util.*;
public class AdjMatrixTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
int e = sc.nextInt();
int[][] adjMatrix = new int[v][v];
for(int i = 0; i < e; ++i) {
int from = sc.nextInt();
int to = sc.nextInt();
adjMatrix[from][to] = adjMatrix[to][from] = 1;
}
for(int[] row : adjMatrix) {
System.out.println(Arrays.toString(row));
}
sc.close();
}
}
7
8
0 1
0 2
0 5
0 6
4 3
5 3
5 4
6 4
이렇게 들어오는 경우는 인접 행렬보다는 인접 리스트나 간선 리스트를 노린 문제인 경우가 많음
import java.util.*;
public class AdjListTest {
static class Node {
int vertex;
Node next;
public Node(int vertex, Node next) {
this.vertex = vertex;
this.next = next;
}
@Override
public String toString() {
return "Node [vertex=" + vertex + ", next=" + next + "]";
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int v = sc.nextInt();
int e = sc.nextInt();
Node[] adjList = new Node[v]; //사실상 헤드리스트
for(int i = 0; i < e; ++i) {
int from = sc.nextInt();
int to = sc.nextInt();
//이렇게 하는 이유는 인접 리스트의 순서는 무의미하기 때문
//그냥 어느 정점과 연결되어있는지만 나타내면 된다.
adjList[from] = new Node(to, adjList[from]);
adjList[to] = new Node(from, adjList[to]);
}
for(Node node : adjList) {
System.out.println(node);
}
sc.close();
}
}
Node [vertex=6, next=Node [vertex=5, next=Node [vertex=2, next=Node [vertex=1, next=null]]]]
Node [vertex=0, next=null]
Node [vertex=0, next=null]
Node [vertex=5, next=Node [vertex=4, next=null]]
Node [vertex=6, next=Node [vertex=5, next=Node [vertex=3, next=null]]]
Node [vertex=4, next=Node [vertex=3, next=Node [vertex=0, next=null]]]
Node [vertex=4, next=Node [vertex=0, next=null]]
adjList[i]
adjList
는 사실상 head list가 된다.public String toString() {
return "Node [vertex=" + vertex + ", next=" + next.toString() + "]";
}
사실상 이런 형태이기 때문