@@ -6,6 +6,7 @@ var GraphNode = function(x, y, id, text) {
6
6
this . state = 'unexplored' ;
7
7
this . cost = Number . POSITIVE_INFINITY ;
8
8
this . parent = null ;
9
+ this . depth = Number . POSITIVE_INFINITY ;
9
10
} ;
10
11
11
12
function getEdgeCostLocation ( x1 , y1 , x2 , y2 ) {
@@ -115,6 +116,7 @@ var GraphProblem = function(nodes, edges, initialKey, nextToExpand) {
115
116
this . nodes [ initialKey ] . state = 'frontier' ;
116
117
this . nodes [ initialKey ] . cost = 0 ;
117
118
this . nodes [ initialKey ] . parent = null ;
119
+ this . nodes [ initialKey ] . depth = 0 ;
118
120
this . initialKey = initialKey ;
119
121
this . frontier = [ initialKey ] ;
120
122
this . explored = [ ] ;
@@ -158,13 +160,12 @@ var GraphProblem = function(nodes, edges, initialKey, nextToExpand) {
158
160
} ;
159
161
} ;
160
162
161
- var GraphAgent = function ( problem ) {
163
+ var GraphAgent = function ( problem , algo ) {
162
164
this . problem = problem ;
163
-
165
+ this . algo = algo ;
164
166
this . expand = function ( nodeKey ) {
165
167
this . problem . removeFromFrontier ( nodeKey ) ;
166
168
this . problem . addToExplored ( nodeKey ) ;
167
-
168
169
let adjacent = this . problem . getAdjacent ( nodeKey ) ;
169
170
for ( var i = 0 ; i < adjacent . length ; i ++ ) {
170
171
let nextNodeKey = adjacent [ i ] . nodeKey ;
@@ -173,10 +174,19 @@ var GraphAgent = function(problem) {
173
174
this . problem . addToFrontier ( nextNodeKey ) ;
174
175
nextNode . cost = adjacent [ i ] . cost + this . problem . nodes [ nodeKey ] . cost ;
175
176
nextNode . parent = nodeKey ;
177
+ nextNode . depth = this . problem . nodes [ nodeKey ] . depth + 1 ;
176
178
}
177
- if ( nextNode . state == 'frontier' && nextNode . cost > adjacent [ i ] . cost + this . problem . nodes [ nodeKey ] . cost ) {
178
- nextNode . cost = adjacent [ i ] . cost + this . problem . nodes [ nodeKey ] . cost ;
179
- nextNode . parent = nodeKey ;
179
+ if ( this . algo == 'ucs' ) {
180
+ if ( nextNode . state == 'frontier' && nextNode . cost > adjacent [ i ] . cost + this . problem . nodes [ nodeKey ] . cost ) {
181
+ nextNode . cost = adjacent [ i ] . cost + this . problem . nodes [ nodeKey ] . cost ;
182
+ nextNode . parent = nodeKey ;
183
+ }
184
+ }
185
+ if ( this . algo == 'dfs' ) {
186
+ if ( nextNode . state == 'frontier' && nextNode . depth < ( this . problem . nodes [ nodeKey ] . depth + 1 ) ) {
187
+ nextNode . depth = this . problem . nodes [ nodeKey ] . depth + 1 ;
188
+ nextNode . parent = nodeKey ;
189
+ }
180
190
}
181
191
}
182
192
} ;
0 commit comments