• 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.

    class Solution {
    private:
        bool search(vector<vector<char>>& board,int i,int j)
        {
            unordered_set<int> hash;
            for(int k=0;k<9;k++)
                if(board[i][k]!='.')
                    hash.insert(board[i][k]-'0'); 
            for(int k=0;k<9;k++)
                if(board[k][j]!='.')
                    hash.insert(board[k][j]-'0');
            for(int x=i/3*3;x<i/3*3+3;x++)
                for(int y=j/3*3;y<j/3*3+3;y++)
                    if(board[x][y]!='.')
                        hash.insert(board[x][y]-'0');        
            if(hash.size()==9return false;
            
            int newi=-1;
            int newj=-1;    
            for(newi=0;newi<9;newi++)
            {
                for(newj=0;newj<9;newj++)
                    if((newi!=i || newj!=j) && board[newi][newj]=='.')                                                                               
                    {
                        for(char k='1';k<='9';k++)
                            if(hash.find(k-'0')==hash.end())
                            {
                                board[i][j]=k;
                                if(search(board,newi,newj)) return true;
                            }
                        board[i][j]='.';
                        return false;
                    }
            }         
            for(char k='1';k<='9';k++)
                if(hash.find(k-'0')==hash.end())
                {
                        board[i][j]=k;    
                }
            return true;
        }
    public:
        void solveSudoku(vector<vector<char> > &board) 
        {
            int x=0;
            int y=0;
            for(int i=0;i<9;i++)
            {
                int j;
                for(j=0;j<9;j++)
                    if(board[i][j]=='.')
                    {
                        x=i;
                        y=j;
                        break;
                    }
                    if(j!=9break;
            }
            search(board,x,y);
        }
    }; 
  • 相关阅读:
    eclipse使用
    模板模式

    异常处理
    内部类
    面向对象三大特征(三)--多态
    java双指针的简单理解
    简单易懂回溯算法
    《深入理解Java虚拟机》之(一、内存区域)
    Java笔记(第七篇 JDBC操作数据库)
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759344.html
Copyright © 2020-2023  润新知