All pastes #288701 Raw Edit

sudoku solver

public text v1 · immutable
#288701 ·published 2006-12-22 14:43 UTC
rendered paste body
// brute force sudoku solver
// by flamingspinach 2006-12-22

        private byte[,] puzzle = new byte[9,9];
 
// The main() function loads an input file into a 9x9 byte array, representing
//    blanks as zeros, calls solved() until it returns true, and then outputs
//    the array back into an output file
 
        private static bool validDigit (byte a, byte b, byte digit) {
            byte a0 = (byte)(a - a%3), b0 = (byte)(b - b%3);
            for (byte c = 0; c < 9; ++c)
                if (puzzle[a, c] == digit || puzzle[c, b] == digit ||
                    puzzle[a0 + c/3, b0 + c%3] == digit) return false;
            return true;
        }
 
        private static bool solved () {
            for (byte a = 0; a < 9; ++a)
                for (byte b = 0; b < 9; ++b)
                    if (puzzle[a, b] == 0) {
                        for (byte digit = 1; digit <= 9; ++digit)
                            if (validDigit(a, b, digit)) {
                                puzzle[a, b] = digit;
                                if (solved()) return true;
                            }
                        puzzle[a, b] = 0;
                        return false;
                    }
            return true;
        }