有效的數獨 -- LeetCode -- 9.14
阿新 • • 發佈:2021-09-17
有效的數獨
請你判斷一個9x9
的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。
- 數字
1-9
在每一行只能出現一次。 - 數字
1-9
在每一列只能出現一次。 - 數字
1-9
在每一個以粗實線分隔的3x3
宮內只能出現一次。(請參考示例圖)
數獨部分空格內已填入了數字,空白格用'.'
表示。
注意:
- 一個有效的數獨(部分已被填充)不一定是可解的。
- 只需要根據以上規則,驗證已經填入的數字是否有效即可。
示例 1:
輸入:board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] 輸出:true
遍歷就行了:
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { int book[10]; memset(book,0,sizeof(book)); for(int i = 0; i < 9; i++){ for(int j = 0; j < 9; j++){ if(board[i][j] >= '0' && board[i][j] <= '9'){//橫著的 int a = board[i][j] - '0'; if(book[a] == 1)return false; else book[a] = 1; } } memset(book,0,sizeof(book)); for(int j = 0; j < 9; j++){ if(board[j][i] >= '0' && board[j][i] <= '9'){//豎著的 int a = board[j][i] - '0'; if(book[a] == 1)return false; else book[a] = 1; } } memset(book,0,sizeof(book)); } for(int i = 0; i < 9; i += 3){ for(int j = 0; j < 9; j += 3){ memset(book,0,sizeof(book)); for(int k = 0; k < 3; k++){//每個 3 * 3的矩形 for(int l = 0; l < 3; l++){ if(board[i + k][j + l] >= '0' && board[i + k][j + l] <= '9'){ int a = board[i + k][j + l] - '0'; if(book[a] == 1)return false; else book[a] = 1; } } } } } return true; } };