File tree Expand file tree Collapse file tree 3 files changed +20
-20
lines changed Expand file tree Collapse file tree 3 files changed +20
-20
lines changed Original file line number Diff line number Diff line change @@ -4,7 +4,7 @@ const Queue = require('../stacks-and-queues/queue');
44 */
55class Graph {
66 constructor ( ) {
7- this . nodes = [ ] ;
7+ this . nodes = { } ;
88 }
99
1010 /**
@@ -42,8 +42,9 @@ Graph.prototype.bfs = function* (node) {
4242 queue . add ( node ) ;
4343
4444 while ( ! queue . isEmpty ( ) ) {
45- const adjacents = this . nodes [ queue . remove ( ) ] ;
46- yield adjacents ;
45+ const current = queue . remove ( ) ;
46+ yield current ;
47+ const adjacents = this . nodes [ current ] || [ ] ;
4748 adjacents . forEach ( function ( adjNode ) {
4849 queue . add ( adjNode ) ;
4950 } ) ;
Original file line number Diff line number Diff line change @@ -36,15 +36,19 @@ describe('Graph', function () {
3636 graph . add ( 1 , 3 ) ;
3737 } ) ;
3838
39- it ( 'should get all adjancent in the first level ' , function ( ) {
39+ it ( 'should get all adjancents from 0 ' , function ( ) {
4040 const bfs = graph . bfs ( 0 ) ;
41- expect ( bfs . next ( ) . value ) . to . eql ( [ 1 , 2 ] ) ;
41+ expect ( bfs . next ( ) . value ) . to . eql ( 0 ) ;
42+ expect ( bfs . next ( ) . value ) . to . eql ( 1 ) ;
43+ expect ( bfs . next ( ) . value ) . to . eql ( 2 ) ;
44+ expect ( bfs . next ( ) . value ) . to . eql ( 3 ) ;
4245 } ) ;
4346
44- it ( 'should get 2nd level adjacents' , function ( ) {
45- const bfs = graph . bfs ( 0 ) ;
46- bfs . next ( ) ;
47- expect ( bfs . next ( ) . value ) . to . eql ( [ 3 ] ) ;
47+ it ( 'should get all adjancents from 1' , function ( ) {
48+ const bfs = graph . bfs ( 1 ) ;
49+ expect ( bfs . next ( ) . value ) . to . eql ( 1 ) ;
50+ expect ( bfs . next ( ) . value ) . to . eql ( 3 ) ;
51+ expect ( bfs . next ( ) . done ) . to . equal ( true ) ;
4852 expect ( bfs . next ( ) . value ) . to . equal ( undefined ) ;
4953 } ) ;
5054 } ) ;
Original file line number Diff line number Diff line change @@ -8,21 +8,16 @@ const Queue = require('../stacks-and-queues/queue');
88 * @returns {boolean }
99 */
1010Graph . prototype . isConnected = function ( node1 , node2 ) {
11- const queue = new Queue ( ) ;
11+ const bfs = this . bfs ( node1 ) ;
12+ let next ;
1213
13- queue . add ( node1 ) ;
14+ do {
15+ next = bfs . next ( ) ;
1416
15- while ( ! queue . isEmpty ( ) ) {
16- const current = queue . remove ( ) ;
17-
18- if ( current === node2 ) {
17+ if ( next . value === node2 ) {
1918 return true ;
2019 }
21-
22- ( this . nodes [ current ] || [ ] ) . forEach ( function ( node ) {
23- queue . add ( node ) ;
24- } ) ;
25- }
20+ } while ( ! next . done ) ;
2621
2722 return false ;
2823} ;
You can’t perform that action at this time.
0 commit comments