Sudoku Solver

来源:互联网 发布:教人做甜品的软件 编辑:程序博客网 时间:2024/05/23 01:30

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.


Solution:

class Solution {public:    void solveSudoku(vector<vector<char>>& board) {        memset(row, true, sizeof(row));        memset(col, true, sizeof(col));        memset(block, true, sizeof(block));        for(int i = 0; i < 9; ++i)            for(int j = 0; j < 9; ++j)            {                if(board[i][j] != '.')                {                    int k = board[i][j] - '0';                    row[i][k] = false;                    col[j][k] = false;                    block[i/3*3+j/3][k] = false;                    }            }                dfs(board, 0);    }        bool dfs(vector<vector<char> >&board, int index)    {        if(index > 80) return true;        int i = index / 9, j = index % 9;        if(board[i][j] != '.') return dfs(board, index + 1);        for(int k = 1; k <= 9; ++k)        {            if(row[i][k] && col[j][k] && block[i/3*3+j/3][k])            {                board[i][j] = k + '0';                row[i][k] = false;                col[j][k] = false;                block[i/3*3+j/3][k] = false;                if(dfs(board, index + 1)) return true;                row[i][k] = true;                col[j][k] = true;                block[i/3*3+j/3][k] = true;            }        }        board[i][j] = '.';                return false;    }private:    bool row[9][10];    bool col[9][10];    bool block[9][10];};


0 0