首页 > 其他 > 详细

Leetcode Sudoku Solver

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!