-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.js
More file actions
162 lines (117 loc) · 3.4 KB
/
graph.js
File metadata and controls
162 lines (117 loc) · 3.4 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
(function main() {
function Node(value)
{
this.value = value;
this.edges = [];
this.parent = null;
this.searched = null;
}
Node.prototype.addEdge = function(node)
{
this.edges.push(node);
}
function Graph()
{
this.nodes = [];
this.graph = {};
this.current = null;
this.start = null;
this.end = null;
this.queue = [];
this.path = '';
}
Graph.prototype.enqueue = function(node)
{
this.queue.push(node);
}
Graph.prototype.dequeue = function()
{
return this.queue.shift();
}
Graph.prototype.setStart = function(start)
{
this.start = start;
this.current = start;
return this.start;
}
Graph.prototype.setEnd = function(end)
{
this.end = end;
return this.end;
}
Graph.prototype.createPath = function()
{
var node = this.breadthFirstSearch();
this.current = node;
var pathArr = [];
while(this.current != undefined) {
pathArr.push(this.current.value);
this.current = this.current.parent;
}
return pathArr;
}
Graph.prototype.getPath = function(order)
{
var order = (order == undefined) ? 'DESC' : order;
var path = this.createPath();
if(order == 'ASC') {
path.reverse();
}
this.path = path.join('->');
return this.path;
}
Graph.prototype.createGraph = function(data)
{
for(var i = 0; i < data.length; i++) {
var node = new Node(i+1);
this.nodes.push(node);
this.graph[i] = node;
}
for(var i = 0; i < this.nodes.length; i++) {
var node = this.nodes[i];
for(var j = 0; j < data[i].length; j++) {
if(data[i][j] == 1) {
node.addEdge(this.nodes[j]);
}
}
}
}
Graph.prototype.breadthFirstSearch = function()
{
if(this.current == this.end){
return true;
}
for(var i = 0; i < this.nodes.length; i++){
var edges = this.nodes[i].edges;
for(var j = 0; j < edges.length; j++) {
var edge = edges[j];
if(i >= this.start.value-1) {
edge.parent = this.nodes[i];
}
if(this.current != edge) {
this.enqueue(edge);
}
}
}
while(this.queue.length > 0){
this.current = this.dequeue();
if(this.current == this.end) {
return this.current;
}
}
}
// Data
var ways = [
[0,1,1,0,0,0],
[0,0,1,0,0,0],
[0,0,0,1,1,0],
[0,0,0,0,0,0],
[0,0,0,0,0,1],
[0,0,0,0,0,0]
];
var _g = new Graph();
_g.createGraph(ways);
_g.setStart(_g.nodes[0]);
_g.setEnd(_g.nodes[5]);
console.log(_g.getPath('ASC'));
}());