leetcode笔记:Sudoku Solver -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    一.题目描述

    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.

    The following photo is a sudoku puzzle…

   

    …and its solution numbers marked in red:<喎?http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwPjxpbWcgYWx0PQ=="这里写图片描述" src="http://www.2cto.com/uploadfile/Collfiles/20151009/20151009085345232.png" title="\" />

    二.题目分析

    注意题目说明了输入保证有且只有一个解,所以试探每一个格子的时候,只需要考虑当前行、列、矩形框满足条件,满足就进入下一个格子试探,不满足回溯,

leetcode笔记:Sudoku Solver

    首先,编写一个函数isValidSudoku()用于测试矩阵当前坐标的值是否合法,检查当前值在行、列以及3*3的矩阵内是否有效。

    于是,对于矩阵中的每个空位'.',尝试填入1~9并检查是否合法,正确则往下一个位置递归。

    只有正确达到矩阵最右下角位置才算填充成功,此时返回填充结果。

    关于回朔算法,以下博客写得浅显易懂,可以参考参考:

    http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html

    http://www.cnblogs.com/Creator/archive/2011/05/20/2052341.html

    三.示例代码

<code class="hljs" cpp="">#include<iostream>#include<vector>using namespace std;class Solution {public:    bool isValidSudoku(vector<vector<char>> &board, int x, int y) {        // 同一列中是否出现相同的数        for (int row = 0; row < 9; ++row)             if ((x != row) && (board[row][y] == board[x][y]))                 return false;        // 同一行中是否出现相同的数        for (int col = 0; col < 9; ++col)            if ((y != col) && (board[x][col] == board[x][y]))                return false;        // 3 * 3方格中是否出现相同的数        for (int row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row)             for (int col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col)                 if ((x != row) && (y != col) && (board[row][col] == board[x][y]))                     return false;        // 满足条件,则返回true        return true;    }    bool internalSolveSudoku(vector<vector<char>> &board) {        for (int row = 0; row < 9; ++row)         {            for (int col = 0; col < 9; ++col)             {                if (board[row][col] == '.')                 {                    for (int i = 1; i <= 9; ++i)                    {                        board[row][col] = '0' + i;                        if (isValidSudoku(board, row, col))                             if (internalSolveSudoku(board))                                 return true;                        // 若当前格子的数不正确,将其重置为'.'                        // 然后进行下一个尝试                        board[row][col] = '.';                    }                    // 0~9均重复,输出false                    return false;                }            }        }        return true;    }    void solveSudoku(vector<vector<char>> &board)     {        internalSolveSudoku(board);    }};</vector<char></vector<char></vector<char></vector></iostream></code>

    结果:

   

    四.小结

    题目规定,输入保证是有效的,因此每填入一个数,无需检查整个矩阵是否合法,只需检查填入数当前行、列和3*3矩阵是否合法即可,

电脑资料

leetcode笔记:Sudoku Solver》(https://www.unjs.com)。

最新文章