問題鏈接: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 問題
它回傳錯誤,我認為這是正確的,但預期的答案是正確的。這怎么可能是一個錯誤的答案。誰能解釋一下。
提前致謝
uj5u.com熱心網友回復:
你誤解了任務。
確定 9 x 9 數獨板是否有效。只有填充的單元格需要根據以下規則進行驗證:
填充的單元格不違反數獨規則。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/405879.html
標籤:
