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

Sudoku Solver

时间:2015-07-14 22:42:09      阅读:154      评论: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.

解:


bool isValid(vector<vector<char>> & board, int x, int y){
        for(int i=0; i<board.size(); i++){
            if(board[i][y]=='.' || i==x)
                continue;
            if(board[x][y]==board[i][y])
                return false;
        }
        
        for(int i=0; i<board[0].size(); i++){
            if(board[x][i]=='.' || i==y)
                continue;
            if(board[x][y]==board[x][i])
                return false;
        }
        
        int startx=x/3*3;
        int starty=y/3*3;
        for(int i=startx; i<startx+3; i++){
            for(int j=starty; j<starty+3; j++){
                if(board[i][j]=='.' || i==x || j==y)
                    continue;
                if(board[i][j]==board[x][y])
                    return false;
            }
        }
        return true;
    }

    bool solveSudo(vector<vector<char>>& board) {
        for(int i=0; i<board.size(); i++){
            for(int j=0; j<board[0].size(); j++){
                if(board[i][j]!='.')
                    continue;
                int k;
                for(k=1; k<10; k++){
                    board[i][j]=k+'0';
                    if(isValid(board, i, j))
                    {
                        if(solveSudo(board))
                            return true;
                    }
                    board[i][j]='.';
                }
                return false;//没有任何判断,直接返回false
            }
        }
        return true;
    }
    
    void solveSudoku(vector<vector<char>>& board) {
        solveSudo(board);
    }


版权声明:本文为博主原创文章,未经博主允许不得转载。

Sudoku Solver

标签:sudoku solver

原文地址:http://blog.csdn.net/jisuanji_wjfioj/article/details/46883247

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