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

Leetcode Sudoku Solver

时间:2014-07-08 00:47:33      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   问题   

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,布布扣

遇到九宫格问题一般都深搜解决

class Solution {
public:
    bool isValidRow(int row , vector<vector<char> >& board){
        vector<int> cnt(10,0);
        for(int col = 0; col < 9; ++ col){
            char item = board[row][col];
            if(item != .){
                if(cnt[item-0]!=0) return false;
                else cnt[item-0]++;
            }
        }
        return true;
    }
    
    bool isValidCol(int col, vector<vector<char> >& board ){
        vector<int> cnt(10,0);
        for(int row = 0; row < 9; ++ row){
            char item = board[row][col];
            if(item != .){
                if(cnt[item-0]!=0) return false;
                else cnt[item-0]++;
            }
        }
        return true;
    }
    
    bool isValidBox(int i,int j, vector<vector<char> >& board){
        vector<int> cnt(10,0);
        for(int row = 3*i;row < 3*i+3; ++row){
            for(int col = 3*j; col < 3*j+3; ++col){
                char item = board[row][col];
                if(item != .){
                    if(cnt[item-0]!=0) return false;
                    else cnt[item-0]++;
                }
            }
        }
        return true;
    }

    bool isValidSudoku(int x, int y,vector<vector<char> > &board) {
        return isValidRow(x,board)&&isValidCol(y,board)&&isValidBox(x/3,y/3,board);
    }
    
    bool dfs(int pos ,vector<vector<char> >& board){
        int n = board.size();
        if(pos == n*n) return true;
        int x = pos/n, y = pos%n;
        if(board[x][y]==.){
            for(char i = 1; i<=9;++ i){
                board[x][y]=i;
                if(isValidSudoku(x,y,board) && dfs(pos+1,board)) return true;
                board[x][y]=.;
            }
        }else{
            if(dfs(pos+1,board)) return true;
        }
        return false;
    }
    
    void solveSudoku(vector<vector<char> > &board) {
        dfs(0,board);
    }
};

 

Leetcode Sudoku Solver,布布扣,bubuko.com

Leetcode Sudoku Solver

标签:style   blog   http   color   os   问题   

原文地址:http://www.cnblogs.com/xiongqiangcs/p/3830465.html

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