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

数独问题

时间:2015-05-24 08:51:53      阅读:128      评论: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.

回答:

bool isValid(vector<vector<char> > &board, int px, int py) {
    int len = board.size();
    
    //check rows and cols.
    for (int i = 0; i < len; ++i)
    {
        if(i != py && board[px][i] == board[px][py] ||
            i != px && board[i][py] == board[px][py])
            return false;
    }

    //check box
    int basex = px/3 * 3;
    int basey = py/3 * 3;
    for (int i = 0; i < 3; ++i)
        for (int j = 0; j < 3; ++j)
        {
            if( basex + i != px &&
                basey + j != py &&
                board[basex + i][basey + j] == board[px][py])
                return false;
        }
    return true;
}

bool currentSudoku(vector<vector<char> > &board) {

    for (int row = 0; row < 9; ++row)
        for (int col = 0; col < 9; ++col)
        {
            if(board[row][col] == ‘.‘)
            {
                for(char num = ‘1‘; num <= ‘9‘; ++num)
                {
                    board[row][col] = num;
                    if(isValid(board, row, col) && currentSudoku(board))
                    return true;
                    board[row][col] = ‘.‘;
                }
                return false;//no number can add in this point.
            }
        }
    return true;
}

void solveSudoku(vector<vector<char> > &board) {
    currentSudoku(board);
}

数独问题

标签:

原文地址:http://www.cnblogs.com/benchao/p/4525337.html

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