生活随笔
收集整理的這篇文章主要介紹了
算法:有效的数独
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
判斷一個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。
數字 1-9 在每一行只能出現一次。
數字 1-9 在每一列只能出現一次。
數字 1-9 在每一個以粗實線分隔的 3x3 宮內只能出現一次。
//有效數獨
class Solution {public boolean isValidSudoku(char[][] board) {// init dataHashMap<Integer, Integer> [] rows = new HashMap[9];HashMap<Integer, Integer> [] columns = new HashMap[9];HashMap<Integer, Integer> [] boxes = new HashMap[9];//初始化for (int i = 0; i < 9; i++) {rows[i] = new HashMap<Integer, Integer>();columns[i] = new HashMap<Integer, Integer>();boxes[i] = new HashMap<Integer, Integer>();}// validate a boardfor (int i = 0; i < 9; i++) {for (int j = 0; j < 9; j++) {char num = board[i][j];if (num != '.') {int n = (int)num;//求出在對應3*3九宮格里面,一共9個int box_index = (i / 3 ) * 3 + j / 3;rows[i].put(n, rows[i].getOrDefault(n, 0) + 1);columns[j].put(n, columns[j].getOrDefault(n, 0) + 1);boxes[box_index].put(n, boxes[box_index].getOrDefault(n, 0) + 1);//判斷里面是否有重復的if (rows[i].get(n) > 1 || columns[j].get(n) > 1 || boxes[box_index].get(n) > 1)return false;}}}return true;}
}
參考地址:https://leetcode-cn.com/problems/valid-sudoku/solution/you-xiao-de-shu-du-by-leetcode/
總結
以上是生活随笔為你收集整理的算法:有效的数独的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。