簡體   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