码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode第36题--Sudoku Solver

时间:2014-10-25 00:46:35      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   sp   div   

题目:

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.

bubuko.com,布布扣

A sudoku puzzle...

 

bubuko.com,布布扣

...and its solution numbers marked in red.

这题相对上题值判断是否合法来说就是更难了。

网上有很多解法,有的复杂有的简洁。我把我理解的记录如下:

思路应该要很明确。利用回溯法。这里是用递归的回溯。我特意复习了下回溯法。就是利用dfs。一直遍历找到符合的解,这个过程有相应的剪枝,剪就通过下面的isValid来进行。需要注意的地方已经给了注释。诉说千字不如代码一行。

class Solution {
    private:
    bool isValid(vector<vector<char> > &board, int x, int y)
    {
        for (int i = 0; i < 9; ++i) // 判断行是否有重复字符
        {
            if (board[i][y] == board[x][y] && i != x)
                return false;
        }
        for (int i = 0; i < 9; ++i) //
        {
            if (board[x][i] == board[x][y] && i != y)
                return false;
        }
        for (int i = 3*(x/3); i < 3*(x/3)+3; ++i) // 子九宫是否有重复
            for (int j = 3*(y/3); j < 3*(y/3)+3; ++j) // 纸上画一个框就能推出其中每个格子的起点和终点与xy的关系
            {
                if (board[i][j] == board[x][y] && i != x && j != y)
                    return false;
            }
        return true; // 都没有就返回合法
    }
public:
    bool solveSudoku(vector<vector<char> > &board)
    {
        // backtracking
        for (int i = 0; i < 9; ++i)
            for (int j = 0; j < 9; ++j)
            {
                if (‘.‘ == board[i][j])
                {
                    for (int k = 1; k <= 9; ++k) // 注意了是1到9,别误以为0到8
                    {
                        board[i][j] = ‘0‘+ k; // = 别写成 == 了,调式了十分钟发现我写成==,泪崩
                        if (isValid(board, i, j) && solveSudoku(board)) // 如果加入的数合法,并且,加入后的有解,那就true
                            return true;
                        board[i][j] = ‘.‘; // if没有返回那就是k取值不合法,所以要重新把元素恢复为‘.‘
                    }
                    return false;
                }
            }
        return true; // 最后一次所有的都填了数字了,解成功了就返回正确
    }
};

 

leetcode第36题--Sudoku Solver

标签:style   blog   http   color   io   ar   for   sp   div   

原文地址:http://www.cnblogs.com/higerzhang/p/4049561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!