Recursive method for solving sudoku

I'm currently studying my second programming course in java and have a problem with an assignment that I need to complete to pass the course. Basically it's about writing a program that recursively solves sudoku with backtracking. This is the algorithm I came up with. I used a 9x9 array to represent the grid which in the beginning is filled with zeroes. checkFill checks whether it's possible to insert a number (var) into a position[i][j]. The problem is that it only solves sudoku partially it always returns false(no solution) and some cells still contain zeroes. What am I doing wrong here?

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Sudoku {
    private int[][] sudoku;
    private JFrame frame;
    private JFormattedTextField[][] sudokuSquares;
    private JButton solve, clear;

    public Sudoku() {
        sudoku = new int[9][9];
        frame = new JFrame("Sudoku Solver");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel northPanel = new JPanel();
        northPanel.setLayout(new GridLayout(9, 9));
        northPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        sudokuSquares = new JFormattedTextField[9][9];
        Font font1 = new Font("SansSerif", Font.BOLD, 20);
        for(int i = 0; i < 9; i++) {
            for(int j = 0; j < 9; j++) {
                sudokuSquares[i][j] = new JFormattedTextField();
                sudokuSquares[i][j].setHorizontalAlignment(JTextField.CENTER);
                sudokuSquares[i][j].setFont(font1);
                sudokuSquares[i][j].setBorder(BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED));
                northPanel.add(sudokuSquares[i][j]);
            }
        }
        setColor();
        frame.add(northPanel, BorderLayout.NORTH);
        JPanel southPanel = new JPanel();
        solve = new JButton("Solve");
        solve.addActionListener(new SolveButtonListener());
        clear = new JButton("Clear");
        clear.addActionListener(new ClearButtonListener());
        southPanel.add(clear);
        southPanel.add(solve);
        frame.add(southPanel, BorderLayout.SOUTH);
        frame.setResizable(false);
        frame.setSize(280, 330);
        frame.setVisible(true);
    }

    private void solveSudoku() {
        boolean hasSolution = solve(0, 0);
        if(hasSolution) {
            JOptionPane.showMessageDialog(frame, "Sudoku has been successfully solved");
        } else {
            JOptionPane.showMessageDialog(frame, "Sudoku has no solution");
        }

    }

    private class SolveButtonListener implements ActionListener {
        @Override
        /**
         * Checks input for errors and outputs the sudoku matrix after it's been solved.
         */
        public void actionPerformed(ActionEvent e) {
            String s;
            setColor();
            for(int i = 0; i < 9; i++) {
                for(int j = 0; j < 9; j++) {
                    s = sudokuSquares[i][j].getText();
                    if(s.isEmpty()) {
                        s = "0";
                    } else if(s.length() > 1 || !Character.isDigit(s.charAt(0)) || s.charAt(0) == '0') {
                        sudokuSquares[i][j].setBackground(Color.RED);
                        JOptionPane.showMessageDialog(frame, "Invalid entry! Please enter a number between 1-9");
                        return;
                    }
                    sudoku[i][j] = Integer.parseInt(s);
                }
            }
            solveSudoku();
            for(int i = 0; i < 9; i++) {
                for(int j = 0; j < 9; j++) {
                    sudokuSquares[i][j].setText(String.valueOf(sudoku[i][j]));
                }
            }
        }
    }

    private class ClearButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            for(int i = 0; i < 9; i++) {
                for(int j = 0; j < 9; j++) {
                    sudokuSquares[i][j].setText("");
                }
            }
            setColor();
        }   
    }

    /**
     * Sets the background color of sudoku cells
     */
    private void setColor() {
        for(int i = 0; i < 9; i++) {
            for(int j = 0; j < 9; j++) {
                if((i / 3 < 1 || i / 3 >= 2) && (j / 3 < 1 || j / 3 >= 2) || 
                        (i / 3 >= 1 && i / 3 < 2) && (j / 3 >= 1 && j / 3 < 2)) {
                    sudokuSquares[i][j].setBackground(new Color(220, 220, 220));
                } else {
                    sudokuSquares[i][j].setBackground(Color.WHITE);
                }
            }
        }
    }

    /**
     * Solves the sudoku through recursive technique
     * @param i row
     * @param j column
     * @return returns true if the sudoku has a solution, returns false otherwise
     */
    private boolean solve(int i, int j) {
        if(i > 8) {
            return true;
        }
        if(sudoku[i][j] == 0) {
            for(int var = 1; var < 10; var++) {
                if(checkFill(i, j, var)) {
                    sudoku[i][j] = var;
                    if(j >= 8) {
                        solve(i + 1, 0);
                    } else {
                        solve(i, j+1);
                    }
                }
            }
        } else {
            if(j >= 8) {
                solve(i + 1, 0);
            } else {
                solve(i, j+1);
            }
        }
        return false;
    }

    /**
     * Checks if var could be inserted at position [i][j]
     * @param i row
     * @param j column
     * @param var number to be checked for possible insertion
     * @return
     */
    private boolean checkFill(int i, int j, int var) {
        for(int a = 0; a < 9; a++) {
            if(sudoku[a][j] == var) {
                return false;
            }
        }
        for(int a = 0; a < 9; a++) {
            if(sudoku[i][a] == var) {
                return false;
            }
        }
        int tempI = (i / 3) * 3;
        int tempJ = (j / 3) * 3;
        for(int a = 0; a < 3; a++) {
            for(int b = 0; b < 3; b++) {
                if(sudoku[tempI + a][tempJ + b] == var)
                    return false;
            }
        }
        return true;
    }

}

So anyone got any ideas?


It seems that your program simply checks if a given number can fit into a given slot, checks the row, column, and local 3x3 grid, and places it there permanently if those three checks pass.

This is problematic since most sudoku will not yield a single possibility on such simple checks.

You'll need to make a list of possible values for each spot, then start using techniques such as double pairs to solve it out further.

Since it's a computer and it's fast, after you use some of these techniques you can start brute forcing it.

A different approach would be to translate the sudoku problem into a SAT formula, feed it into a SAT solver, and translate the solution back into a sudoku solution. There are very advanced SAT solvers these days that can handle 9x9 sudoku very quickly. Here is a more in-depth explanation.


In your solve method, you test whether sudoku[i][j]==0 before you make a change. That means that once you place a number, whether it's right or wrong, you never change it. You need to be able to back out of errant moves.


You can find a simplified java Sudoku program here.http://www.heimetli.ch/ffh/simplifiedsudoku.html

if you can share you full source code including the method checkFill, we can assist you in debuging further

链接地址: http://www.djcxy.com/p/96162.html

上一篇: 使用递归方法的数独生成器算法

下一篇: 用于解决数独的递归方法