判断一个 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 存在, 因此这个数独是无效的。
方法一:哈希表 遍历9x9格,若数字第一次出现则加入哈希表,若第二次出现则在原来value值上+1。
import java.util.HashMap; class Solution { public boolean isValidSudoku(char[][] board) { HashMap<Integer,Integer>[] rows = new HashMap[9]; HashMap<Integer,Integer>[] colume = new HashMap[9]; HashMap<Integer,Integer>[] board_son = new HashMap[9]; for(int k=0;k<9;k++){ rows[k] = new HashMap<Integer,Integer>(); colume[k] = new HashMap<Integer,Integer>(); board_son[k] = new HashMap<Integer,Integer>(); } for(int i = 0;i<9;i++){ for(int j=0;j<9;j++){ char num = board[i][j]; if(board[i][j] != '.'){ int n = (int)num; int board_index = (i/3)*3+(j/3); rows[i].put(n,rows[i].getOrDefault(n,0)+1); colume[j].put(n,colume[j].getOrDefault(n,0)+1); board_son[board_index].put(n,board_son[board_index].getOrDefault(n,0)+1); if((rows[i].get(n) > 1) || colume[j].get(n) > 1 || board_son[board_index].get(n) > 1)return false; } } } return true; } }方法二:数组 由于给定的表是9x9,因此可以考虑用数组来代替哈希表,可以优化时间复杂度。
class Solution { public boolean isValidSudoku(char[][] board) { int[][] rows = new int[9][9]; int[][] colume = new int[9][9]; int[][] board_son = new int[9][9]; for(int i = 0;i < 9;i++){ for(int j = 0;j < 9;j++){ if(board[i][j] != '.'){ int num = board[i][j] - '1'; int board_index = (i/3)*3 + (j/3); if(rows[i][num] == 1)return false; else rows[i][num] = 1; if(colume[j][num] == 1)return false; else colume[j][num] = 1; if(board_son[board_index][num] == 1)return false; else board_son[board_index][num] = 1; } } } return true; } }来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/valid-sudoku