Skip to content

Instantly share code, notes, and snippets.

@kavitshah8
Last active August 29, 2015 14:00
Show Gist options
  • Save kavitshah8/11240600 to your computer and use it in GitHub Desktop.
Save kavitshah8/11240600 to your computer and use it in GitHub Desktop.
Implements Depth First Search Algorithm to avoid modifying global variables.
var graph = {
A : { "value": 20, "neighbours": ["D","B"] },
B : { "value": 10, "neighbours": ["A","E","C"] },
C : { "value": 30, "neighbours": ["B"] },
D : { "value": 20, "neighbours": ["A","E"] },
E : { "value": 90, "neighbours": ["D","B","F"] },
F : { "value": 100, "neighbours": ["E"] }
};
// Implements Breadth First Search Algorithm (with necessary modifications)
// It assumes that it has Read Only Rights for the Global Objects
// Time complexity of algorithm is Big-O (# Edges + # Vertices)
function dfs(){
var visitedNodes = {};
var max = 0;
for ( var key in graph ) {
if( !visitedNodes[key] ){
max = dfsVisit( key, visitedNodes, max );
};
};
return max;
};
function dfsVisit( key, visitedNodes, max ){
if ( graph[key].value > max) {
max = graph[key].value;
};
visitedNodes[key] = true;
for ( var i = 0; i < graph[key]['neighbours'].length; i++ ) {
var v = graph[key]['neighbours'][i];
if ( graph[v].value > max) {
max = graph[v].value;
};
if( !visitedNodes[v] ){
dfsVisit( v, visitedNodes, max );
};
return max;
};
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Cyan Phone Interview</title>
</head>
<body>
<div id="mocha"><p><a href=".">Index</a></p></div>
<div id="messages"></div>
<div id="fixtures"></div>
<script src="mocha.js"></script>
<script src="chai.js"></script>
<script>mocha.setup('bdd')</script>
<script src="app.js"></script>
<script src="test.js"></script>
<script>mocha.run();</script>
</body>
</html>
var expect = chai.expect;
describe( 'Breadth First Search ', function() {
it( 'Graph Existance', function () {
expect( graph ).to.be.an( 'object' );
expect( graph['A'] ).to.be.have.property( 'value' );
expect( graph['A'] ).to.be.have.property( 'neighbours' );
} );
it( 'Depth First Search', function() {
var max = dfs( );
expect( max ).to.equal( 100 );
} );
it('Depth First Search Visit', function ( ) {
var key = 'A';
var visitedNodes = {};
var max ;
dfsVisit( key, visitedNodes, max );
expect( visitedNodes[key] ).to.be.true;
expect( visitedNodes[ 'B' ] ).to.be.undefined;
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment