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

leetcode[37]Sudoku Solver

时间:2015-02-10 14:56:42      阅读:173      评论: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.

技术分享

A sudoku puzzle...

 

技术分享

...and its solution numbers marked in red.

#define NUM 9
class Solution {
public:
bool isValidij(vector<vector<char> > &board, int i, int j) 
{
    for (int k=0;k<NUM;k++)
    {
        if (k!=j)
        {
            if(board[i][k]==board[i][j])return false;
        }
        if (k!=i)
        {
            if(board[k][j]==board[i][j])return false;
        }
    }
    int a=i/3*3;
    int b=j/3*3;
    for (int ii=a;ii<a+3;ii++)
    {
        for (int jj=b;jj<b+3;jj++)
        {
            if(ii!=i&&jj!=j)
            {
                if (board[ii][jj]==board[i][j])return false;
            }
        }
    }
    return true;
}
bool solve(vector<vector<char> > &board) 
{
    for (int i=0;i<NUM;i++)
    {
        for (int j=0;j<NUM;j++)
        {
            if (board[i][j]==.)
            {
                int k=1;
                for (;k<=NUM;k++)
                {
                    board[i][j]=0+k;
                    if (isValidij(board,i,j))
                    {
                        if(solve(board))return true;
                    }
                    board[i][j]=.;
                }
                return false;
            }
        }
    }
    return true;
}
void solveSudoku(vector<vector<char> > &board) 
{
        solve(board);
}
};

 

leetcode[37]Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/Vae98Scilence/p/4283592.html

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