-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph_TopologicalSorting.js
More file actions
84 lines (71 loc) · 2.21 KB
/
Graph_TopologicalSorting.js
File metadata and controls
84 lines (71 loc) · 2.21 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
위상 정렬
- 모든 간선의 방향이 왼쪽에서 오른쪽
- 우선 검색과 달리 현재 정점과 인접한 모든 정점을 방문한 다음 인접리스트를 모두 확인하고 현재 정점을 스택으로 푸시
*/
function Graph (v) {
this.vertices = v;
this.edges = 0;
this.adj = [];
for (var i = 0; i < this.vertices; i++) {
this.adj[i] = [];
this.adj[i].push("");
};
this.addEdge = addEdge;
this.showGraph = showGraph;
function addEdge (v, w) {
this.adj[v].push(w);
this.adj[w].push(v);
this.edges++;
}
function showGraph () {
var visited = [];
for (var i = 0; i < this.vertices; i++) {
process.stdout.write(this.vertexList[i] + " -> ");
visited.push(this.vertexList[i]);
for (var j = 0; j < this.vertices; j++) {
if (this.adj[i][j] != undefined) {
if (visited.indexOf(this.vertexList[j]) < 0)
process.stdout.write(this.vertexList[j] + ' ');
};
};
console.log("");
visited.pop();
};
}
this.topSort = topSort;
this.topSortHelper = topSortHelper;
function topSort() {
var stack = [];
var visited = [];
for (var i = 0; i < this.vertices; i++) {
visited[i] = false;
};
for (var i = 0; i < this.vertices; i++) {
if(visited[i] == false)
this.topSortHelper(i, visited, stack);
};
for (var i = 0; i < stack.length; i++) {
if(stack[i] != undefined && stack[i] != false)
console.log(this.vertexList[stack[i]]);
};
}
function topSortHelper(v, visited, stack) {
visited[v] = true;
for(var w in this.adj[v]){
if(visited[w] == false)
this.topSortHelper(visited[w], visited, stack);
}
stack.push(v);
}
}
var g = new Graph(6);
g.addEdge(1, 2);
g.addEdge(2, 5);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(0, 1);
g.vertexList = ["CS1", "CS2", "DataStructure", "AssemblyLanguage", "OperatingSystems", "Algorithms"];
g.showGraph();
console.log("");
g.topSort();