[Leetcode] [Java] Sudoku Solver

Source: Internet
Author: User

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

Related Keywords:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• Sales Support

1 on 1 presale consultation

• After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.