Sudoku solver in Java, using backtracking and recursion

后端 未结 6 498
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  死守一世寂寞
    2020-12-09 16:32

    Firstly, a suggestion for optimization: While checking whether, the number you're going to put in a cell, is already present in the same row, column or minigrid, you don't have to run a loop or something like that. You can perform an instant check by array indexing.

    Consider 3 9x9 boolean double dimensional arrays:

    boolean row[9][9], col[9][9], minigrid[9][9]
    

    We'll be using the first array for checking whether a number is present in the same row, the second array for checking if a number is present in the same column, and the third for the mini grid.

    Supposing you want to put a number n in your cell i, j. You will check if row[i][n-1] is true. If yes, then ith row already contains n. Similarly, you will check if col[j][n-1] and minigrid[gridnum][n-1] is true.

    Here gridnum is the index of mini grid, where the cell you want to insert a number, lies in. To calculate mini grid number for cell i,j, divide i & j by 3, multiply the integral part of former with 3, and add it to the integral part of the latter.

    This how it looks:

    gridnum = (i/3)*3 + j/3
    

    By looking at values of i/3 and j/3 for all i and j, you will get an idea of how this works. Also, if you put a number in a cell, update the arrays too. E.g. row[i][n-1] = true

    If there is a part you don't understand, post a comment and I'll edit my answer to explain it.

    Secondly, using recursion & backtracking to solve this is pretty easy.

    boolean F( i, j) // invoke this function with i = j = 0
    {
    If i > 8: return true // solved
    
    for n in 1..9
     {
     check if n exists in row, column, or mini grid by the method I described
    
     if it does: pass ( skip this iteration )
    
     if it doesn't
      {
       grid[i][j] = n
       update row[][], col[][], minigrid[][]
    
       if F( if j is 8 then i+1 else i, if j is 8 then 0 else j+1 ) return true // solved
      }
     }
     return false // no number could be entered in cell i,j
    }
    

提交回复
热议问题