r/programmingchallenges • u/babygame • Jun 01 '11
Coloring a grid
Make a program to color in the squares of an (n x m) grid (with some number of colors > 2) such that no two same colors touch.
There is a 'brute force' way, and (at least one) more 'elegant' solution as well.
Edit: I didn't specify-- try one that will output a different pattern each time. It's a nicer problem, I think :)
21
Upvotes
View all comments
Show parent comment
2
u/awap Sep 09 '11 edited Sep 09 '11
The implementation is linked from my post.
I wasn't arguing for his original position, because he was making a silly pedantic remark: the obvious iteration order is to go either through them sequentially, either row-major or column major. Asserting that that's not what you meant just seems silly.
What I'm arguing against is the statement you made that iteration order doesn't matter. That statement stands on its own; I don't need to read the whole thread to see what you said. Also, I'm pretty sure it's wrong.
You should take his original suggestion and actually do the complexity analysis instead of just asserting that it must be fast on a gameboy or whatever.
Edit, Here's a hint: do the complexity analysis for a 2xN grid. Ignore the rows, and estimate how many backtracks are needed for a particular column (it's 2c). And every time we backtrack at a column, we have to redo all of the columns below it. It gets bad.
There are 2 obvious improvements to the algorithm. One is to use backjumping instead of ordinary backtracking to go directly to the cell that caused the conflict. The other is to use the current state of the cell to adjust our search order. Both of these might make it violate the uniformly random property that we are looking for. I'm not really sure, and it's time to get back to real work...