Sudoku solver in Java, using backtracking and recursion

后端 未结 6 492
隐瞒了意图╮
隐瞒了意图╮ 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

    i suggest passing both the current row and column to the recursive method then find all allowed numbers for THAT cell, for each allowed number recursivly call the method for the next column (or next row if at last column) and undo the move if it leads to a dead track

    public boolean fillCell(int r, int c) {
        if last row and last cell {
            //report success
            return true
        }
        for i 1 to 9 {
            if can place i on r, c {
                board[r][c] = i
                if !fillCell(next empty row, next empty column) { //DONT change r or c here or you will not be able to undo the move
                    board[r][c] = 0
                }
                /*
                else {
                    return true; //returning true here will make it stop after 1 solution is found, doing nothing will keep looking for other solutions also
                }
                */
    
            }
        }
        return false        
    }
    

提交回复
热议问题