1. 程式人生 > 資訊 >OPPO 手機在拉丁美洲迅速擴張,在墨西哥市場佔比達 12%

OPPO 手機在拉丁美洲迅速擴張,在墨西哥市場佔比達 12%

判斷一個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。

數字 1-9 在每一行只能出現一次。
數字 1-9 在每一列只能出現一次。
數字 1-9 在每一個以粗實線分隔的 3x3 宮內只能出現一次。

上圖是一個部分填充的有效的數獨。

數獨部分空格內已填入了數字,空白格用 '.' 表示。

示例 1:

輸入:
[
["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:

輸入:
[
["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 存在, 因此這個數獨是無效的。

說明:

一個有效的數獨(部分已被填充)不一定是可解的。
只需要根據以上規則,驗證已經填入的數字是否有效即可。
給定數獨序列只包含數字 1-9 和字元 '.' 。
給定數獨永遠是 9x9 形式的。
解題思路:HashSet,不可儲存重複元素,用3個HashSet,分別儲存第i行、第i列和第i個3x3的九宮格中的元素,每處理一個元素,若不為空,將正在處理的當前元素,新增到所屬的行、列以及3x3的九宮格中,若新增失敗,表明所屬的行、列或者3x3九宮格中有重複元素,返回false;若全部掃描完,返回true。
ps:
Hashset裡的Add():如果某元素不在集合中,Add()方法就把該元素新增到集合中。在其返回值Boolean中,返回元素是否新增的資訊;
Character 類在物件中包裝一個基本型別 char 的值

程式碼如下:

class Solution {
    public boolean isValidSudoku(char[][] board) {
        //最外層迴圈,每次迴圈並非只是處理第i行,而是處理第i行所有列以及第i個3x3的九宮格
        for(int i = 0; i < 9; i++){
            HashSet<Character> line = new HashSet<>();
            HashSet<Character> col = new HashSet<>();
            HashSet<Character> cube = new HashSet<>();
            for(int j = 0; j < 9; j++){
                if('.' != board[i][j] && !line.add(board[i][j]))//加上去的不為空,也不重複(重複為false)
                    return false;
                if('.' != board[j][i] && !col.add(board[j][i]))
                    return false;
                int m = 3 * i / 3 + j / 3;
                int n = 3 * i % 3 + j % 3;
                if('.' != board[m][n] && !cube.add(board[m][n]))
                    return false;
            }
        }
        return true;
    }
}