Sudoku solver in Java, using backtracking and recursion

后端 未结 6 496
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 16:01

I am programming a Sudoku solver in Java for a 9x9 grid.

I have methods for:

  • printing the grid

  • initializing the board with given val

6条回答
  •  Happy的楠姐
    2020-12-09 16:26

    I would check each cell and go back a recursion step if no solution can be found.

    In more detail: Go to next cell, if value x == 0, check if x+1 would be valid, if true, go to next cell by calling the method recursively with the next possible cell. If the number is not valid check x+2 etc. if no number is valid return false and repeat the x+1 step in the previous call. If you hit a cell with a number inside, do not call the recursion but directly go to the next, thus you need not to flag any pre entered cells.

    Pseudo code:

    fillcell cell
     while cell is not 0
      cell = next cell
     while cell value < 10
      increase cell value by one
      if cell is valid 
        if fillcell next cell is true
          return true
    return false
    

    Not sure if this correct but it should show the idea.

提交回复
热议问题