Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.


A sudoku puzzle...


...and its solution numbers marked in red.

unsigned int row[9];
unsigned int column[9];
unsigned int grid[3][3];
bool found;

class Solution {
public:
    void visit(vector<vector<char> > &board, int i, int j)
    {
        if (board[i][j] != '.')
        {
            if (j+1 < 9)
            {
                visit(board, i, j+1);
            }
            else if (i+1 < 9)
            {
                visit(board, i+1, 0);
            }
            else
            {
                found = true;
                return;
            }
        }
        else
        {
            for (int k = 1; k <= 9; k++)
            {
                unsigned int factor = 1<<k;
                if ((row[i]&factor) == 0
                    && (column[j]&factor) == 0
                    && (grid[i/3][j/3]&factor) == 0)
                {
                    row[i] |= factor;
                    column[j] |= factor;
                    grid[i/3][j/3] |= factor;
                    board[i][j] = k + '0';
                    if (j+1 < 9)
                    {
                        visit(board, i, j+1);
                    }
                    else if (i+1 < 9)
                    {
                        visit(board, i+1, 0);
                    }
                    else
                    {
                        found = true;
                        return;
                    }

                    if (!found)
                    {
                        row[i] ^= factor;
                        column[j] ^= factor;
                        grid[i/3][j/3] ^= factor;
                        board[i][j] = '.';
                    }
                }
            }
        }
    }

    void solveSudoku(vector<vector<char>>& board) {
        memset(row, 0, 9*sizeof(unsigned int));
        memset(column, 0, 9*sizeof(unsigned int));
        memset(grid, 0, 9*9*sizeof(unsigned int));
        found = false;

        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
            {
                if (board[i][j] != '.')
                {
                    row[i] |= (1 << (board[i][j]-'0'));
                }
                if (board[j][i] != '.')
                {
                    column[i] |= (1 << (board[j][i]-'0'));
                }
            }
        }

        for (int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
            {
                if (board[j][i] != '.')
                {
                    grid[i/3][j/3] |= (1 << (board[i][j]-'0'));
                }
            }
        }
    
        visit(board, 0, 0); 
    }
};


你可能感兴趣的:(Sudoku Solver)