Number of ways to color N | Javascript program for the above approach ; Recursive function to count the ways ; Base case ; Let initialise answer to 0 ; Color each uncolored block according to the given condition ; If any block is uncolored ; Check if adjacent blocks are colored or not ; Color the block ; recursively iterate for next uncolored block ; Uncolored for the next recursive call ; Return the final count ; Function to count the ways to color block ; Mark which blocks are colored in each recursive step ; Function call to count the ways ; Number of blocks ; Number of colored blocks ; Function call
let mod = 1000000007 ; function countWays ( colored , count , n ) { if ( count == n ) { return 1 ; } let answer = 0 ; for ( let i = 1 ; i < n + 1 ; i ++ ) { if ( colored [ i ] == 0 ) { if ( colored [ i - 1 ] == 1 colored [ i + 1 ] == 1 ) { colored [ i ] = 1 ; answer = ( answer + countWays ( colored , count + 1 , n ) ) % mod ; colored [ i ] = 0 ; } } } return answer ; } function waysToColor ( arr , n , k ) { let colored = Array . from ( { length : n + 2 } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < k ; i ++ ) { colored [ arr [ i ] ] = 1 ; } return countWays ( colored , k , n ) ; } let N = 6 ; let K = 3 ; let arr = [ 1 , 2 , 6 ] ; document . write ( waysToColor ( arr , N , K ) ) ;