File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed
Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change 1+ /*
2+ * Author: Mayank
3+ * Bellman-Ford Algorithm implementation in JavaScript
4+ * Detects shortest paths and checks for negative weight cycles in a graph.
5+ */
6+
7+ // Bellman-Ford with negative cycle detection
8+
9+ function bellmanFordNegativeCycle ( graph , vertices , start ) {
10+ const dist = new Array ( vertices ) . fill ( Infinity )
11+ dist [ start ] = 0
12+
13+ // relax all edges (V - 1) times
14+ for ( let i = 0 ; i < vertices - 1 ; i ++ ) {
15+ for ( let [ u , v , w ] of graph ) {
16+ if ( dist [ u ] !== Infinity && dist [ u ] + w < dist [ v ] ) {
17+ dist [ v ] = dist [ u ] + w
18+ }
19+ }
20+ }
21+
22+ // check for negative cycle
23+ for ( let [ u , v , w ] of graph ) {
24+ if ( dist [ u ] !== Infinity && dist [ u ] + w < dist [ v ] ) {
25+ return { hasNegativeCycle : true , dist }
26+ }
27+ }
28+
29+ return { hasNegativeCycle : false , dist }
30+ }
31+
32+ export { bellmanFordNegativeCycle }
Original file line number Diff line number Diff line change 1+ /*
2+ * Test file for Bellman-Ford Negative Cycle Detection
3+ */
4+
5+ import { bellmanFordNegativeCycle } from '../BellmanFordNegativeCycle.js'
6+
7+ test ( 'should find shortest distance without negative cycle' , ( ) => {
8+ const graph = [
9+ [ 0 , 1 , 4 ] ,
10+ [ 0 , 2 , 5 ] ,
11+ [ 1 , 2 , - 3 ] ,
12+ [ 2 , 3 , 4 ]
13+ ]
14+ const result = bellmanFordNegativeCycle ( graph , 4 , 0 )
15+
16+ expect ( result . hasNegativeCycle ) . toBe ( false )
17+ expect ( result . dist [ 3 ] ) . toBe ( 6 ) // shortest distance from 0 to 3
18+ } )
19+
20+ test ( 'should detect negative cycle' , ( ) => {
21+ const graph = [
22+ [ 0 , 1 , 1 ] ,
23+ [ 1 , 2 , - 1 ] ,
24+ [ 2 , 0 , - 1 ]
25+ ]
26+ const result = bellmanFordNegativeCycle ( graph , 3 , 0 )
27+
28+ expect ( result . hasNegativeCycle ) . toBe ( true )
29+ } )
You can’t perform that action at this time.
0 commit comments