zoukankan      html  css  js  c++  java
  • Leetcode 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...

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

    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);
        }
    };
  • 相关阅读:
    订餐系统之微信点餐
    Alfred工具
    使用密码记录工具keepass来保存密码
    一步一步实战扩展 ASP.NET Route,实现小写 URL、个性化 URL
    提高性能,抛弃反射
    -串行化与反串行化
    JavaScript 命名空间
    .net SoapHeader验证
    [置顶] Android Sensor系统剖析(4.0)(下)
    VirtualBox虚拟机下Windows登录密码破解方法(阿里云推荐码:1WFZ0V,立享9折!)
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3830465.html
Copyright © 2011-2022 走看看