《原神攻略》夜泊石收集路線指引
題目描述
請你判斷一個 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示例 2:
輸入:
board =
[["8","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"]]
輸出:false
解釋:除了第一行的第一個數字從 5 改為
8 以外,空格內其他數字均與 示例1 相同。 但由於位於左上角的 3x3 宮內有兩個 8 存在, 因此這個數獨是無效的。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/valid-sudoku
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
Java
class Solution { public boolean isValidSudoku(char[][] board) { int[][] row = new int[9][9]; int[][] col = new int[9][9]; int[][][] square = new int[3][3][9]; for(int i = 0; i < 9; ++i){ for(int j = 0; j < 9; ++j){ char c = board[i][j]; if(c != '.'){ int index = c - '0' - 1; row[i][index]++; col[j][index]++; square[i / 3][j / 3][index]++; if(row[i][index] > 1 || col[j][index] > 1 || square[i / 3][j / 3][index] > 1){ return false; } } } } return true; } }