繁体   English   中英

数独求解器代码给出了意想不到的结果

[英]Sudoku Solver code gives unexpected result

问题链接: https://leetcode.com/problems/valid-sudoku/description/

下面是我的数独求解器代码。 如果数独是可解的,我应该返回 true,否则返回 false。

class Solution {
public:
    bool solveSudoku(vector<vector<char>> &board, int row, int col) {
        // If the position is now at the end of the 9*9 grid
        if(row == 8 and col == 9) return true;
        // if column has reached upper bound
        if(col==9)  {
            row++;
            col=0;
        }
        // For characters other than dot move to the next position
        if(board[row][col]!='.') return solveSudoku(board,row,col+1); 
        for(int i=1; i<=9; i++) {
            char num='0'+i;
            if(isValid(board, row, col, num)) {
                board[row][col]=num;
                if(solveSudoku(board,row,col+1)) return true;
            }
            board[row][col]='.';
        }
        return false;
    }
    bool isValid(vector<vector<char>> &board, int row, int col, char num) {
        int i,j;
        /* Checking if its duplicated on the same row */
        for(i=0; i<9; i++) {
            if(i!=col && board[row][i] == num) {
                return false;
            }
        }
        /* Checking if its duplicated on the same col */
        for(i=0; i<9; i++) {
            if(i!=row && board[i][col] == num) {
                return false;
            }
        }
        /* Checking if its duplicated inside the 3*3 grid */
        int rowOffset=row-(row%3);
        int colOffset=col-(col%3);
        for(i=0; i<3;i++) {
            for(j=0;j<3;j++) {
                if((rowOffset+i)!=row && (colOffset+j)!=col && board[rowOffset+i][colOffset+j] == num) {
                    return false;
                }
            }
        }
        return true;
    }
    bool isValidSudoku(vector<vector<char>>& board) {
        if(solveSudoku(board, 0, 0)) return true;
        return false;
    }
};

对于以下测试输入

[[".","8","7",  "6","5","4",  "3","2","1"],
 ["2",".",".",  ".",".",".",  ".",".","."],
 ["3",".",".",  ".",".",".",  ".",".","."],

 ["4",".",".",  ".",".",".",  ".",".","."], 
 ["5",".",".",  ".",".",".",  ".",".","."],
 ["6",".",".",  ".",".",".",  ".",".","."],

 ["7",".",".",  ".",".",".",  ".",".","."],
 ["8",".",".",  ".",".",".",  ".",".","."],
 ["9",".",".",  ".",".",".",  ".",".","."]]

注意:这是一个 leetcode 问题

它返回错误,我认为这是正确的,但预期的答案是正确的。 这怎么可能是一个错误的答案。 谁能解释一下。

提前致谢

你误解了任务。

确定 9 x 9 数独板是否有效。 只有填充的单元格需要根据以下规则进行验证:

填充的单元格不违反数独规则。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM