Title Description:
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells is indicated by the character ‘.‘
.
Assume that there would be is only one unique solution.
A Sudoku Puzzle ...
... and its solution numbers marked in red.
Problem Solving Ideas:
The subject uses backtracking and HashSet methods. For each blank position, the temptation is to use a number between ' 1 '-' 9 ', if the number is added in the case that satisfies the Sudoku rule, the character is added to the position, and the test goes down; If the temptation fails, return to the current step, and another character continues the temptation.
The code is as follows:
public class Solution {public void Solvesudoku (char[][] board) {hashset[] row = new Hashset[9]; hashset[] col = new Hashset[9]; hashset[] cell = new Hashset[9];inithashset (board, Row, col, cell), solve (board, row, col, cell);} public boolean solve (char[][] board, hashset[] row, hashset[] col,hashset[] cell) {for (int i = 0; i < 9; i++) { T j = 0; J < 9; J + +) {if (board[i][j] = = '. ') {for (char c = ' 1 '; c <= ' 9 "; C + +) {if (Isvalidsudoku (board, I, J, C, Row, col, cell)) {Board[i][j] = C;row[i].add (c); c Ol[j].add (c); Cell[3 * (I/3) + J/3].add (c); if (Solve (board, row, col, cell)) return True;else {board[i][j] = '. '; Row[i].remove (c); Col[j].remove (c); Cell[3 * (I/3) + j/3].remove (c);}}} return false;}}} return true;} public boolean Isvalidsudoku (char[][] board, int i, Int J, Char c,hashset[] row, hashset[] col, hashset[] cell) {if (row[i ].contains (c) | | Col[j].contains (c) | | Cell[3 * (I/3) + j/3].contains (c)) return False;return true; public void Inithashset (char[][] board, Hashset[] row,hashset[] col, hashset[] cell) {for (int i = 0; i < 9; i++) {Row[i] = new hashset<character> (); Col [I] = new hashset<character> (); Cell[i] = new hashset<character> ();} for (int i = 0, i < 9; i++) {for (int j = 0; J < 9; J + +) {if (board[i][j]! = '. ') {Row[i].add (board[i][j]); Col[j].add (Board[i][j]); Cell[3 * (I/3) + J/3].add (Board[i][j]);}}}}
Java [Leetcode 37]sudoku Solver