36. 有效的数独 Valid Sudoku
Determine if a 9 x 9
Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the nine
3 x 3
sub-boxes of the grid must contain the digits1-9
without repetition.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentioned rules.
方法:
遍历9*9的二维矩阵即可,将出现的数据放在map里
public boolean isValidSudoku(char[][] board) { Map<Integer,Map<Character,Integer>> rows = new HashMap<>(); Map<Integer,Map<Character,Integer>> cols = new HashMap<>(); Map<Integer,Map<Character,Integer>> block = new HashMap<>(); for (int i = 0; i < 9; i++){ Map<Character,Integer> rowMap= new HashMap<>(); rows.put(i,rowMap); Map<Character,Integer> colMap= new HashMap<>(); cols.put(i,colMap); Map<Character,Integer> blockMap= new HashMap<>(); block.put(i,blockMap); } for (int i =0 ;i < 9; i++){ for(int j = 0; j < 9; j++){ if (board[i][j] == '.') continue; if (rows.get(i).containsKey(board[i][j])) return false; else rows.get(i).put(board[i][j],1); if (cols.get(j).containsKey(board[i][j])) return false; else cols.get(j).put(board[i][j],1); if(block.get(i/3*3+j/3).containsKey(board[i][j])) return false; else block.get(i/3*3+j/3).put(board[i][j],1); } } return true; }
参考链接:
https://leetcode.com/problems/valid-sudoku/
https://leetcode-cn.com/problems/valid-sudoku/