LeetCode Sudoku Solver 回溯

原创 2015年07月08日 11:20:37

思路:

DFS。时间复杂度O(9^4),空间复杂度O(1)。
下棋添子,下完一步下另一步,不行就回溯。

class Solution {
private:
    bool isValid(vector<vector<char>> &board, int i, int j) {
        //check col
        for(int row = 0; row < 9; ++row) {
            if(row != i && board[row][j] == board[i][j]) {
                return false;
            }
        }
        //check row
        for(int col = 0; col < 9; ++col) {
            if(col != j && board[i][col] == board[i][j]) {
                return false;
            }
        }
        //check cube
        for(int row = i - i%3; row < i + (3 - i%3); ++row) {
            for(int col = j - j%3; col < j + (3 - j%3); ++col) {
                if(row == i && col == j) continue;
                if(board[row][col] == board[i][j]) {
                    return false;
                }
            }
        }
        return true;
    }

    bool dfs(vector<vector<char>>& board) {
        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) {
                        board[i][j] = '0' + k;
                        if(isValid(board, i, j) && dfs(board)) {
                            return true;
                        }
                        board[i][j] = '.';
                    }
                    return false;
                }
            }
        }
        return true;
    }
public:
    void solveSudoku(vector<vector<char>>& board) {
        dfs(board);
    }
};

LeetCode OJ:Sudoku Solver

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

LeetCode Sudoku Solver

题目 Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated ...

Leetcode Sudoku Solver My Submissions Question

Leetcode Sudoku Solver My Submissions Question ,本问题主要是使用递归的思想,不断的试探,直到得出结果,同时也得注意记录已有值的方法,主要是横向、纵向、...

Leetcode-Sudoku Solver

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

Leetcode Sudoku Solver

这次抽到的是解数独问题 数独 每九个中不能有重复数字 每一行不能有 每一列不能有 所以我们应该对每个单元格用1-9进行尝试,满足前三个检查可能是正确答案,对每个可能进行递归。写了一个递...

LeetCode-37.Sudoku Solver

https://leetcode.com/problems/sudoku-solver/ Write a program to solve a Sudoku puzzle by fillin...

[LeetCode] Sudoku Solver

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

LeetCode - Sudoku Solver

https://leetcode.com/problems/sudoku-solver/ 这道题我发现大部分的解决方法都是加一个isValid函数,来判断当前数字是否合法。 比如: http:/...

LeetCode 36 Sudoku Solver

Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by t...

Leetcode #37. Sudoku Solver 数独求解 结题报告

1 解题报告首先可以看下昨天的 Leetcode #36. Valid Sudoku 数独游戏验证 解题报告 数独的求解,这道题可以假设给定的这个是正确的做法就只能是暴力的回溯了。。 方法是回溯,用...
  • MebiuW
  • MebiuW
  • 2016年04月08日 23:58
  • 845
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode Sudoku Solver 回溯
举报原因:
原因补充:

(最多只允许输入30个字)