Problem: If you are playing a Sudoku game, provide a way to validate if a configuration is a valid solution to Sudoku?
Solution: Basically, there are 27 zones (9 columns, 9 rows and 9 squares) you need to check. To check each zone, we can use a bit vector (2 bytes long) to check duplicates. For every number n in the zone, we do 1 << n and check whether the nth bit of current flag is "1" or "0" (by using "&"). If it is "1", then duplicates detected. Otherwise we update the current flag and move on.
Caution: Some one propose to calculate the sum and product of all the numbers in a zone, to see if the sum are produce are 45 and 9! respectively. However, this doesn't guarantee a solution to Sudoku. For example, 4+4+4+1+9+5+9 +7 +2 = 45 and also their product equals to 9!. Moreover, the time complexity is of the similar level as the solution proposed.
No comments:
Post a Comment