zoukankan      html  css  js  c++  java
  • 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);
        }
    }; 
  • 相关阅读:
    调整vmware虚拟机硬盘空间的方法
    微型网络IP转换工具
    初观线程(1)
    Linux逻辑盘卷管理LVM详解(转载)
    微型IP转换工具V1.0升级版
    android 模拟器一键root
    android自用小软件"小毛毛起床啦!“<1>
    很久没更新博客了,写下最近的情况
    解决skype突然无法启动的问题(原创)
    OllyDBG处理C++ EH exception异常
  • 原文地址:https://www.cnblogs.com/erictanghu/p/3759344.html
Copyright © 2011-2022 走看看