Condition to check if first row was painted in previous column
else if ( prev == 1 ) { vis [ col ] = true ; res += ( helper ( col + 1 , 0 , painted + 1 , 2 , N , P , K ) ) % mod ; res += ( helper ( col + 1 , 0 , painted + 1 , 3 , N , P , K ) ) % mod ; vis [ col ] = false ; if ( prevCol + 1 < P ) { res += ( helper ( col + 1 , prevCol + 1 , painted , 0 , N , P , K ) ) % mod ; } }