File tree 2 files changed +22
-22
lines changed
2 files changed +22
-22
lines changed Original file line number Diff line number Diff line change 6
6
* @see https://en.wikipedia.org/wiki/Graph_coloring
7
7
*/
8
8
function mColoring ( graph , m ) {
9
- const colors = new Array ( graph . length ) . fill ( 0 ) ;
9
+ const colors = new Array ( graph . length ) . fill ( 0 )
10
10
11
11
// Check if it's safe to color a vertex with a given color.
12
12
function isSafe ( vertex , color ) {
13
13
for ( let i = 0 ; i < graph . length ; i ++ ) {
14
14
if ( graph [ vertex ] [ i ] && colors [ i ] === color ) {
15
- return false ;
15
+ return false
16
16
}
17
17
}
18
- return true ;
18
+ return true
19
19
}
20
20
21
21
// Use backtracking to try and color the graph.
22
22
function solveColoring ( vertex = 0 ) {
23
23
if ( vertex === graph . length ) {
24
- return true ;
24
+ return true
25
25
}
26
26
27
27
for ( let color = 1 ; color <= m ; color ++ ) {
28
28
if ( isSafe ( vertex , color ) ) {
29
- colors [ vertex ] = color ;
30
-
29
+ colors [ vertex ] = color
30
+
31
31
if ( solveColoring ( vertex + 1 ) ) {
32
- return true ;
32
+ return true
33
33
}
34
34
35
35
// If no solution, backtrack.
36
- colors [ vertex ] = 0 ;
36
+ colors [ vertex ] = 0
37
37
}
38
38
}
39
- return false ;
39
+ return false
40
40
}
41
41
42
42
// If coloring is possible, return the colors.
43
43
if ( solveColoring ( ) ) {
44
- return colors ;
44
+ return colors
45
45
}
46
- return null ;
46
+ return null
47
47
}
48
48
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'
2
2
3
3
describe ( 'MColoringProblem' , ( ) => {
4
4
it ( 'should color a triangle with 3 colors' , ( ) => {
5
5
const graph = [
6
6
[ 0 , 1 , 1 ] ,
7
7
[ 1 , 0 , 1 ] ,
8
8
[ 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
+ } )
13
13
14
14
it ( 'should not color a triangle with 2 colors' , ( ) => {
15
15
const graph = [
16
16
[ 0 , 1 , 1 ] ,
17
17
[ 1 , 0 , 1 ] ,
18
18
[ 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