LeetCode 36. Valid Sudoku (effective Sudoku) solution ideas and methods
Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles-The Rules.
The Sudoku board cocould be partially filled, where empty cells are filled with the character '.'.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Train of Thought: The question is very simple, mainly about Rule understanding. The sudoku game has never been played, and I don't know any rules. I thought the number of any 9 squares 1-9 is 1, which of the following rules does not consider the number of 1-9 in a specific nine-digit grid. The code is cool, but the idea is clear as follows:
Public class Solution {// set it to static variable static Map
Map = new HashMap
(); Public boolean isValidSudoku (char [] [] board) {// judge each row for (int I = 0; I <board. length; I ++) {initMap (); // each time you need to initialize for (int j = 0; j <board [0]. length; j ++) {// It is a number if (board [I] [j]> = '0' & board [I] [j] <= '9 ') {if (map. get (board [I] [j])> 0) {// repeated number return false;} else {map. put (board [I] [j], 1) ;}} else if (board [I] [j]! = '. ') {// Return false if there are spaces or characters other than 0-9; // directly return false }}// judge each column for (int I = 0; I <board [0]. length; I ++) {initMap (); // each time you need to initialize for (int j = 0; j <board. length; j ++) {// It is a number if (board [j] [I]> = '0' & board [j] [I] <= '9 ') {if (map. get (board [j] [I])> 0) {// repeated number return false;} else {map. put (board [j] [I], 1) ;}} else if (board [j] [I]! = '. ') {// Return false if there are spaces or characters other than 0-9; // return false directly }}// determine the 9-sector grid for (int I = 0; I <board. length-2; I = I + 3) {// row {for (int j = 0; j <board [0]. length-2; j = j + 3) {initMap (); // initialize for (int m = I; m <I + 3; m ++) {for (int n = j; n <j + 3; n ++) {// The number if (board [m] [n]> = '0' & board [m] [n] <= '9') {if (map. get (board [m] [n])> 0) {// repeated number return false;} else {map. put (board [m] [n], 1) ;}} else if (board [m] [n]! = '. ') {// Return false if there is a space or a character other than 0-9; // directly return false }}} return true ;} // initialize map. Each key is assigned 0 private void initMap () {for (char I = '0'; I <= '9'; I ++) {map. put (I, 0 );}}}