Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8260117
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T03:01:12+00:00 2026-06-08T03:01:12+00:00

def answer_solve_sudoku(__grid): res = check_sudoku(__grid) if res is None or res is False: return

  • 0
def answer_solve_sudoku(__grid):

    res = check_sudoku(__grid)
    if res is None or res is False:
        return res

    grid = copy.deepcopy(__grid)

    # find the first 0 element and change it to each of 1..9,
    # recursively calling this function on the result
    for row in xrange(9):
        for col in xrange(9):
            if grid[row][col] == 0:
                for n in xrange(1, 10):
                    grid[row][col] = n
                    new = answer_solve_sudoku(grid)
                    if new is not False:
                        return new
                # backtrack
                return False

    # if we get here, we found no zeros and so we're finished
    return grid

Here is the code, and check_sudoku(grid) can return if a grid is a valid sudoku or not.

I just can’t understand the recursion part, I tried to write down the process on the paper, but it failed everytime, how is backtraking working? and what is new? if the answer_solve_sudoku(grid) is valid?

I know it sets every 0 to 1..9, and checks if it’s a valid grid or not, but I just can’t draw the whole process on the paper. And can’t really understand how the backtrack is working.

btw, is there any advice of understanding recursion code?

Best Regards,

Sheng Yun

EDIT

I read the code again and again, and now I have some understanding, but I’m just not that sure about this, it will be kind if anyone gives me some comments.

1, return new will only be called when the solver found the solution, and this will be called right after return grid

2, when will

# backtrack
return False

be called? if the next solution isn’t right, check_sudoku(__grid) will return False, and if the next solution is right, it will call another answer_solve_sudoku(grid) till it gets the right solution, and when it gets the right solution, it will return grid and then return new. So when is:

# backtrack
return False

called?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-08T03:01:14+00:00Added an answer on June 8, 2026 at 3:01 am

    Rather than writing this out on paper, I have a better recommendation. Format the code to show you a visual representation of what the logic is doing. Here is a way to do that:

    def print_counter(val, msg):
        print "%s[%d] %s" % (" "*val, val, msg)
    
    def answer_solve_sudoku(__grid, counter=0):
    
        res = check_sudoku(__grid)
        if res is None or res is False:
            return res
    
        grid = copy.deepcopy(__grid)
    
        for row in xrange(9):
            for col in xrange(9):
                if grid[row][col] == 0:
                    for n in xrange(1, 10):
                        grid[row][col] = n
                        print_counter(counter,"test: (row %d, col %d) = %d" % (row,col,n))
                        new = answer_solve_sudoku(grid, counter+1)
                        if new is not False:
                            print_counter(counter, "answer_solve_sudoku() solved: returning")
                            return new
                    # backtrack
                    print_counter(counter, "backtrack")
                    return False
    
        print_counter(counter, "**SOLVED! Returning back up to top**")
        return grid
    
    from pprint import pprint 
    solution = answer_solve_sudoku(easy_grid)
    pprint(solution)
    

    What I did was create a little printer function that will print a number and indent the message by that many spaces. Then in your answer_solve_sudoku, I gave it a default counter value of 0, and always pass in counter+1 to each recursive call. That way as the depth grows, so will the number. And I put printer functions along to way to visually illustrate what is happening.

    What you will see is something like this:

    [0] test: (row 0, col 2) = 1
    [0] test: (row 0, col 2) = 2
    [0] test: (row 0, col 2) = 3
    [0] test: (row 0, col 2) = 4
     [1] test: (row 0, col 3) = 1
      [2] test: (row 0, col 4) = 1
      [2] test: (row 0, col 4) = 2
      [2] test: (row 0, col 4) = 3
        ... 
             [45] test: (row 7, col 7) = 8
             [45] test: (row 7, col 7) = 9
             [45] backtrack
            [44] test: (row 7, col 5) = 6
            [44] test: (row 7, col 5) = 7
        ... 
                   [51] test: (row 8, col 6) = 6
                   [51] test: (row 8, col 6) = 7
                    [52] **SOLVED! Returning back up to top**
                   [51] answer_solve_sudoku() solved: returning
                  [50] answer_solve_sudoku() solved: returning
                 [49] answer_solve_sudoku() solved: returning
        ... 
      [2] answer_solve_sudoku() solved: returning
     [1] answer_solve_sudoku() solved: returning
    [0] answer_solve_sudoku() solved: returning
    

    return new will only be called when the solver found the solution,
    and this will be called right after return grid

    Yes, when a call to answer_solve_sudoku makes its way through that whole loop without failing and reaches the bottom, it has succeeded and returns the grid. The caller will then get that grid as a result to new = answer_solve_sudoku(grid) and return that. The grid will make its way back up each returning call on the stack.

    when will backtrack occur?

    Because you are creating a copy of the grid in each recursion, unless that step finds the solution, the changes it made to that grid will be discarded, since once we return back up one step we will be back to our previous grid state. It tries to go as far as it can with that solution until it runs past the value of 9.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

def download_if_dne(href, filename): if os.path.isfile(filename): # print 'already downloaded:', href return False else: if
def update @album = Album.find(params[:id]) if @album.update_attributes(params[:album]) redirect_to(:action=>'list') else render(:action=>'edit') end end A Rails
def partial(template, *args) options = args.extract_options! options.merge!(:layout => false) if collection = options.delete(:collection) then
def self.get(server) return unless server server = server.to_s if klass = @handlers[server] obj =
How can I find the point where the first derivative of my equation equals
payment-tags.py @register.simple_tag def has_purchased(user_id): payments = Payment.objects.all(user__id=user_id) return PaymentObjects(payments) class PaymentObjects(template.Node): def __init__(self, payments):
In this answer a singleton decorator is demonstrated as such def singleton(cls): instances =
def self.jq_column_models COLUMN_NAME.collect {|x| {:name => x.to_s, :width => 80, :format => 'integer' if
def On_Instrumentation_StartAnimation(): Syntax : On_Instrumentation_StartAnimation() Purpose : Fired if the animation is started Parameters
def myFunc( a, b ): def innerFunc( c ): print c innerFunc( 2 )

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.