- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGraph.java
More file actions
Latest commit
44 lines (38 loc) · 1.68 KB
/
Copy pathGraph.java
File metadata and controls
44 lines (38 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
importjava.util.LinkedList;
publicclassGraph {
privateintV; // 그래프의 정점 갯수
LinkedList<Integer> adjListArray[]; // 그래프의 정점을 저장할 인접리스트 배열
publicGraph(intV) { // 그래프 생성자, 정점과 인접리스트 배열을 초기화 한다.
this.V = V;
adjListArray = newLinkedList[V];
for (inti = 0; i < V; i++) {
adjListArray[i] = newLinkedList<>();
}
}
// 그래프 출력 메소드
publicvoidprintGraph() {
for (intv = 0; v < V; v++) {
System.out.print(v);
for (Integeri : adjListArray[v]) {
System.out.print(" => " + i);
}
System.out.print("\n");
}
}
// 양방향 간선 생성 메소드
staticvoidaddEdge(Graphgraph, intsrc, intdest) {
graph.adjListArray[src].add(dest);
graph.adjListArray[dest].add(src);
}
publicstaticvoidmain(String[] args) {
intV = 5; // 정점의 갯수는 5개 (0, 1, 2, 3, 4)
Graphgraph = newGraph(V); // 그래프 초기화
addEdge(graph, 0, 1); // 0번과 1번을 정점으로 하는 간선을 생성한다.
addEdge(graph, 0, 2); // 0번과 2번을 정점으로 하는 간선을 생성한다.
addEdge(graph, 1, 2); // 1번과 2번을 정점으로 하는 간선을 생성한다.
addEdge(graph, 1, 3); // 1번과 3번을 정점으로 하는 간선을 생성한다.
addEdge(graph, 2, 4); // 2번과 4번을 정점으로 하는 간선을 생성한다.
addEdge(graph, 3, 4); // 3번과 4번을 정점으로 하는 간선을 생성한다.
graph.printGraph();
}
}