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

[leetcode]Sudoku Solver

时间:2014-12-28 11:42:52      阅读:360      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   

问题描述:

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 sudoku(int row, int col, int num, vector<vector<char> >& board){ //C++
        if(num == 81) 
            return true;


        int nextcol,nextrow;
        if(col == 8){
            nextcol = 0;
            nextrow = row+1;
        }else{
            nextcol = col+1;
            nextrow = row;   
        }

        if(board[row][col] != '.'){
            num++;
            bool suc;
            return sudoku(nextrow,nextcol,num,board);
            
        }
        
        for(int i = 1; i <=9; i++){
            bool isfilled = fillcell(row,col,i,board);
             bool suc;

            if(isfilled){
                board[row][col] = i +'0';
                num++;
                
                
                suc = sudoku(nextrow,nextcol,num,board);
                
                if(suc == true)
                    return true;
                
                board[row][col] = '.';
                num--;
            }
        }
        
        return false;
    }
    bool fillcell(int row, int col, int value, vector<vector<char> >& board){
            char ch = value +'0';
            for(int i =0; i < 9; i++)
            {
                if(board[row][i] == ch)
                    return false;
                if(board[i][col] == ch)
                    return false;
            }
            int tmprow = row/3*3;
            int tmpcol = col/3*3;
            for(int i = tmprow; i < tmprow+3; i++)
                for(int j = tmpcol; j<tmpcol+3; j++)  //error 
                    if(board[i][j] == ch)
                        return false;
            
            return true;
        
    }
    void solveSudoku(vector<vector<char> > &board) {
          sudoku(0,0,0,board);
        
    }


[leetcode]Sudoku Solver

标签:leetcode   算法   

原文地址:http://blog.csdn.net/chenlei0630/article/details/42212363

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