Title:
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.
Test Instructions:
Write a program to solve Sudoku problems by filling in whitespace.
These spaces are characters‘.‘
填充。
You can assume that there is only one solution.
Algorithm Analysis:
* The first reaction is the N queen problem. It's just a little bit of trying to fill in the numbers, not going back, until it's all filled up.
*
* If it is not possible to try from 0~9 to a grid, then the whole Sudoku is no solution, return false is good.
*
* For the whole chessboard all '. ' Are all finished, then you can return to true.
AC Code:
public class solution{public void Solvesudoku (char[][] board) {SOLVESUDOKUDFS (board); } private static Boolean Solvesudokudfs (char[][] board) {for (int. i=0;i<9;i++) {for (int j=0;j<9;j++) {if (Board[i] [j]== '. ') {for (int k=1;k<=9;k++) {board[i][j]= (char) (k + ' 0 ');//Try if (IsValid (board,i,j) && Solvesudokudfs (board)) Return true;board[i][j]= '. '; /fallback}return false;}}} return true;} private static Boolean isValid (char[][] board, int i, int j) {for (int k=0;k<9;k++) { if (k!=j && board[i][k]==board[i][j]) return false; } for (int k=0;k<9;k++) {if (k!=i && board[k][j]==board[i][j]) r Eturn false; } for (int row = i/3*3, row<i/3*3+3; row++) {for (int col=j/3*3; col<j/3*3+3; col++) {if ((Row!=i | | col!=j) && BOARD[ROW][COL]==BOARD[I][J]) return false; }} return true; } }
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Sudoku Solver