Sudoku solving algorithm with back-tracking

后端 未结 2 1519
一个人的身影
一个人的身影 2021-02-15 14:14

I\'m looking to implement a very simple algorithm that uses brute-force back-tracking to solve Sudoku grids. The problem I\'m facing is that in my implementation I included two

相关标签:
2条回答
  • 2021-02-15 14:46

    Actually, you don't really need a stack or recursion. You just need an ordered way to visit the cells (see code below). This solution will not give you stackoverflow like a recursive version would.

    I would create an initial matrix to label pre-solved cells:

    public boolean[][] findSolved(int[][] grid){
        boolean[][] isSolved = new boolean[9][9];        
    
        for(int i=0; i<9; i++)
            for(int j=0; j<9; j++)
                isSolved[i][j] = grid[i][j] != 0;
    
        return isSolved;
    }
    

    Then go forwards or backwards through the cells based on if you are backtracking:

    public boolean solve(int[][] grid){
        boolean[][] isSolved = findSolved(grid);
        int row, col, k = 0;
        boolean backtracking = false;
    
        while( k >= 0 && k < 81){
            // Find row and col
            row = k/9;
            col = k%9;
    
            // Only handle the unsolved cells
            if(!isSolved[row][col]){
                grid[row][col]++;
    
                // Find next valid value to try, if one exists
                while(!isSafe(grid, row, col) && grid[row][col] < 9)
                    grid[row][col]++;
    
                if(grid[row][col] >= 9){
                    // no valid value exists. Reset cell and backtrack
                    grid[row][col] = 0;
                    backtracking = true;
                } else{
                    // a valid value exists, move forward
                    backtracking = false;
                }
            }
    
            // if backtracking move back one, otherwise move forward 1.
            k += backtracking ? -1:1
        }
    
        // k will either equal 81 if done or -1 if there was no solution.
        return k == 81;
    }
    
    0 讨论(0)
  • 2021-02-15 14:52

    I was able to store the 'row' and 'col' values of the empty cells that I kept loosing with each recursive call by storing them in a Stack instance variable of the Sudoku class. The findNextZero() method pushed the 'row' and 'col' values into two empty stacks. Then, I restructured the rest of the program to access this information through the peek() method, and in case i had to backtrack I simply popped the last two values and set the number on the grid corresponding to those values to 0.

    0 讨论(0)
提交回复
热议问题