Skip to content

Commit 099f2f5

Browse files
committed
2017-09-30
1 parent be1a20b commit 099f2f5

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

4/topolagicalsort/Readme.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# 위상정렬(topological sort)
2+
유향 그래프의 꼭짓점들(vertex)을 변의 방향을 거스르지 않도록 나열하는 것을 의미한다.<br>
3+
비순환 <strong>유향 그래프(directed acyclic graph)</strong> 이다.
4+
1. 자기 자신을 가리키는 변이 없는 꼭짓점을 찾음.
5+
2. 찾은 꼭짓점을 출력하고 출력한 꼭짓점과 그 꼭짓점에서 출발하는 변을 삭제
6+
3. 아직 그래프에 꼭짓점이 남아있으면 단계 1로 돌아가고, 아니면 알고리즘을 종료시킨다.

4/topolagicalsort/ex/Main.class

1.62 KB
Binary file not shown.

4/topolagicalsort/ex/Main.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.*;
2+
3+
public class Main {
4+
static int n;
5+
static int m;
6+
static int s;
7+
8+
public static void main(String args[]) {
9+
Scanner scanner = new Scanner(System.in);
10+
n = scanner.nextInt();
11+
m = scanner.nextInt();
12+
ArrayList<Integer>[] adj_list = new ArrayList[n + 1]; // 인접(adjacency)한 점을 담을 리스트
13+
14+
for (int i = 1; i <= n; i++) {
15+
adj_list[i] = new ArrayList<>();
16+
}
17+
18+
int ind[] = new int[n + 1];
19+
for (int i = 0; i < m; i++) {
20+
int u = scanner.nextInt();
21+
int v = scanner.nextInt();
22+
adj_list[u].add(v); // u(시작 정점) -> v(도착 정점)로 간다.
23+
ind[v]++; // v 랑 연결된 점의 개수
24+
}
25+
Queue<Integer> q = new LinkedList<>();
26+
for (int i = 1; i <= n; i++) {
27+
if (ind[i] == 0) { // 도착정점이 아니면
28+
q.add(i); // 큐에 담는다.
29+
}
30+
}
31+
while (!q.isEmpty()) { // 큐가 비어있지 않으면
32+
int here = q.poll(); // 큐에서고꺼내고 지금 위치로 저장한다.
33+
System.out.print(String.valueOf(here) + ' '); // 지금 위치를 출력하고
34+
for (int i = 0; i < adj_list[here].size(); i++) { // 인접한 점 즉, u -> here 에서 u를 찾아낸다.
35+
int there = adj_list[here].get(i); // u가 있으면,
36+
ind[there]--;// u랑 연결된 점의 개수를 1개 빼주고
37+
if (ind[there] == 0) { // u랑 연결된 점의 개수가 0일시
38+
q.add(there); // 큐에 u를 담는다.
39+
}
40+
}
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)