Leetcode DFS Sudoku Solver

Source: Internet
Author: User

Sudoku Solver Total accepted:11799 Total submissions:56732 My submissions

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character'.'.

You may assume that there will be only one unique solution.


A Sudoku puzzle...


... And its solution numbers marked in red.



question: Fill in the sudoku and return whether the data is filled successfully
train of thought: DFS
find a position that has not been filled, and enter a number in the 0-9 format, determine whether or not.
if it is reasonable, it can be transferred to a similar problem, so it can be implemented recursively.
bool solvesudoku (vector & board)
whether the result is successfully filled with the sudoku whose current status is Board

Bool isvalid (const vector <char> & board, int X, int y) {// check the row for (Int J = 0; j <9; ++ J) if (J! = Y & Board [x] [J] = Board [x] [Y]) return false; // check the column for (INT I = 0; I <9; ++ I) if (I! = X & Board [I] [Y] = Board [x] [Y]) return false; // check the small block for (INT I = 0; I <3; ++ I) for (Int J = 0; j <3; ++ J) {If (! (X/3*3 + I = x & Y/3*3 + J = y) & Board [X/3*3 + I] [Y/3*3 + J] = Board [x] [Y]) return false;} return true ;} bool solvesudoku (vector <char> & board) {for (INT I = 0; I <9; ++ I) {for (Int J = 0; j <9; ++ J) {If (Board [I] [J] = '. ') {for (int K = 0; k <9; ++ K) {board [I] [J] = K + '1'; If (isvalid (board, i, j) & solvesudoku (board) return true; Board [I] [J] = '. ';} return false ;}}} return true; // This sentence is missing and Wa has been written many times}


Leetcode DFS Sudoku Solver

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.