37. Sudoku Solver

Problem:

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

A sudoku solution must satisfy all of the following rules:

  1. Each of the digits 1-9 must occur exactly once in each row.
  2. Each of the digits 1-9 must occur exactly once in each column.
  3. Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

Empty cells are indicated by the character '.'.


A sudoku puzzle...


...and its solution numbers marked in red.

Note:

  • The given board contain only digits 1-9 and the character '.'.
  • You may assume that the given Sudoku puzzle will have a single unique solution.
  • The given board size is always 9x9.

思路

采用递归的思想。基本的思路是按照从上到下,从左到右的顺序,在所有的空格处依次填入1-9的数字,然后判断填进去之后是否满足数独的要求,如果满足则继续填下一个空格,不满足则在当前空格处填入下一个数字。在填的时候利用了递归的思想,如果checkSudoku(board, i, j, c),则说明数独有效,再进行solveSudoku(board, i, j+1)操作。

值得注意的是,虽然题目的函数返回值为空,但事实上的输出为board,所以我们在传递参数的时候传递的是board的引用&board,如果不传递引用则board不会被改变。

Solution (C++):

public:
    void solveSudoku(vector<vector<char>>& board) {
        solveSudoku(board, 0, 0);
    }
private:
    bool checkSudoku(vector<vector<char>> &board, int i, int j, char val) {            //检查填入val后数独是否有效
        int row = i - i%3, column = j - j%3;
        for (int x = 0; x < 9; x++) {
            if (board[i][x] == val)  return false;
            if (board[x][j] == val)  return false;
            if (board[row+x/3][column+x%3] == val)  return false;
        }
        return true;
    }
    bool solveSudoku(vector<vector<char>> &board, int i, int j) {
        if (i == 9)  return true;                                //说明数独填完
        if (j == 9)  return solveSudoku(board, i+1, 0);          //说明第i行填完,开始填第i+1行
        if (board[i][j] != '.')  return solveSudoku(board, i, j+1);
        
        for (char c = '1'; c <= '9'; c++) {
            if (checkSudoku(board, i, j, c)) {
                board[i][j] = c;
                if (solveSudoku(board, i, j+1))  return true;
                board[i][j] = '.';
            }
        }
        return false;
    }

性能

Runtime: 16 ms  Memory Usage: 8.9 MB

相关链接如下:

知乎:littledy

欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/dysjtu1995/p/12293872.html