[Leetcode] (python): 037-sudoku Solver

Source: Internet
Author: User

Source of the topic

https://leetcode.com/problems/sudoku-solver/

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.

Test instructions Analysis

Input:a Unsolved Sudoku

Output:a solved Sudoku

Conditions: Meet the Sudoku condition, just need to find an answer

Topic ideas

Using the DFS idea, each empty 1-9 of the choice, if not satisfied then backtracking; the satisfied condition is isvalid (), which satisfies the row, and the column and the small nine squares have not used two identical elements (that is, numbers)

AC Code (PYTHON)

1 classsolution (object):2     defSolvesudoku (self, Board):3         """4 : Type BOARD:LIST[LIST[STR]]5 : Rtype:void does not return anything, modify board In-place instead.6         """7         defisValid (x, y):8temp =Board[x][y]9Board[x][y] ='R'Ten              forIinchRange (9): One                 ifBoard[i][y] = =Temp: A                     returnFalse -              forIinchRange (9): -                 ifBoard[x][i] = =Temp: the                     returnFalse -              forIinchRange (3): -                  forJinchRange (3): -                     ifBOARD[X/3 * 3 + I][Y/3 * 3 + j] = =Temp: +                         returnFalse -Board[x][y] =Temp +             returnTrue A  at         defDFS (board): -              forIinchRange (9): -                  forJinchRange (9): -                     ifBOARD[I][J] = ='.': -                          forKinch '123456789': -BOARD[I][J] =k in                             ifIsValid (I,J) andDFS (board): -                                 returnTrue toBOARD[I][J] ='.' +                         returnFalse -             returnTrue the              * DFS (board) $         

[Leetcode] (python): 037-sudoku Solver

Related Article

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.