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

LeetCode 037 Sudoku Solver

时间:2015-02-07 18:49:37      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

题目要求:Sudoku Solver

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.

 

分析:

参考网址:http://www.cnblogs.com/panda_lin/archive/2013/11/04/sudoku_solver.html

回溯法尝试所有解0_o

① 对于每个空位‘.‘,遍历1~9,check合理之后递归;

② check的时候,不用遍历整个数独,只需检查加入的行、列和块就足够了。

 

代码如下:

class Solution {
public:
    bool isValidSudoku(vector<vector<char> > &board, int x, int y) {
        int row, col;
        
        // Same value in the same column?
        for (row = 0; row < 9; ++row) {
            if ((x != row) && (board[row][y] == board[x][y])) {
                return false;
            }
        }
        
        // Same value in the same row?
        for (col = 0; col < 9; ++col) {
            if ((y != col) && (board[x][col] == board[x][y])) {
                return false;
            }
        }
        
        // Same value in the 3 * 3 block it belong to?
        for (row = (x / 3) * 3; row < (x / 3 + 1) * 3; ++row) {
            for (col = (y / 3) * 3; col < (y / 3 + 1) * 3; ++col) {
                if ((x != row) && (y != col) && (board[row][col] == board[x][y])) {
                    return false;
                }
            }
        }
        
        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] = .;
                    }
                    
                    return false;
                }
            }
        }
        
        return true;
    }
    
    void solveSudoku(vector<vector<char> > &board) {
        internalSolveSudoku(board);
    }
};

 

LeetCode 037 Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/510602159-Yano/p/4279125.html

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