File tree Expand file tree Collapse file tree 2 files changed +22
-22
lines changed Expand file tree Collapse file tree 2 files changed +22
-22
lines changed Original file line number Diff line number Diff line change 66 * @see https://en.wikipedia.org/wiki/Graph_coloring
77 */
88function mColoring ( graph , m ) {
9- const colors = new Array ( graph . length ) . fill ( 0 ) ;
9+ const colors = new Array ( graph . length ) . fill ( 0 )
1010
1111 // Check if it's safe to color a vertex with a given color.
1212 function isSafe ( vertex , color ) {
1313 for ( let i = 0 ; i < graph . length ; i ++ ) {
1414 if ( graph [ vertex ] [ i ] && colors [ i ] === color ) {
15- return false ;
15+ return false
1616 }
1717 }
18- return true ;
18+ return true
1919 }
2020
2121 // Use backtracking to try and color the graph.
2222 function solveColoring ( vertex = 0 ) {
2323 if ( vertex === graph . length ) {
24- return true ;
24+ return true
2525 }
2626
2727 for ( let color = 1 ; color <= m ; color ++ ) {
2828 if ( isSafe ( vertex , color ) ) {
29- colors [ vertex ] = color ;
30-
29+ colors [ vertex ] = color
30+
3131 if ( solveColoring ( vertex + 1 ) ) {
32- return true ;
32+ return true
3333 }
3434
3535 // If no solution, backtrack.
36- colors [ vertex ] = 0 ;
36+ colors [ vertex ] = 0
3737 }
3838 }
39- return false ;
39+ return false
4040 }
4141
4242 // If coloring is possible, return the colors.
4343 if ( solveColoring ( ) ) {
44- return colors ;
44+ return colors
4545 }
46- return null ;
46+ return null
4747}
4848
49- export { mColoring } ;
49+ export { mColoring }
Original file line number Diff line number Diff line change 1- import { mColoring } from '../MColoringProblem' ;
1+ import { mColoring } from '../MColoringProblem'
22
33describe ( 'MColoringProblem' , ( ) => {
44 it ( 'should color a triangle with 3 colors' , ( ) => {
55 const graph = [
66 [ 0 , 1 , 1 ] ,
77 [ 1 , 0 , 1 ] ,
88 [ 1 , 1 , 0 ]
9- ] ;
10- const solution = mColoring ( graph , 3 ) ;
11- expect ( solution ) . not . toBeNull ( ) ;
12- } ) ;
9+ ]
10+ const solution = mColoring ( graph , 3 )
11+ expect ( solution ) . not . toBeNull ( )
12+ } )
1313
1414 it ( 'should not color a triangle with 2 colors' , ( ) => {
1515 const graph = [
1616 [ 0 , 1 , 1 ] ,
1717 [ 1 , 0 , 1 ] ,
1818 [ 1 , 1 , 0 ]
19- ] ;
20- const solution = mColoring ( graph , 2 ) ;
21- expect ( solution ) . toBeNull ( ) ;
22- } ) ;
23- } ) ;
19+ ]
20+ const solution = mColoring ( graph , 2 )
21+ expect ( solution ) . toBeNull ( )
22+ } )
23+ } )
You can’t perform that action at this time.
0 commit comments