简体   繁体   中英

Java Sudoku Solver, does it work the same with different sudoku sizes?

I have a sudoku solver that works with 9x9 sudokus perfectly. I would like to get it to work with 9x6 sudokus and other sizes too. Is it possible to just change this function?

You can see that the "9" is always hardcoded. So I tried changing these values to 9 and 6 but the result is only 0s in my solution.

So before I continue messing around with this, is it even possible to change this to support different grid sizes without changing the functions?

    public boolean solve(int i, int j, int[][] cells) {

        if (i == 9) {
            i = 0;
            if (++j == 9) {
                return true;
            }
        }
        if (cells[i][j] != 0)
        {
            return solve(i + 1, j, cells);
        }

        for (int val = 1; val <= 9; ++val) {
            if (legal(i, j, val, cells)) {
                cells[i][j] = val;
                if (solve(i + 1, j, cells)) {
                    return true;
                }
            }
        }
        cells[i][j] = 0;
        return false;
    }

    public static boolean legal(int i, int j, int val, int[][] cells) {
        for (int k = 0; k < 9; ++k) // rij
        {
            if (val == cells[k][j]) {
                return false;
            }
        }

        for (int k = 0; k < 9; ++k) // kolom
        {
            if (val == cells[i][k]) {
                return false;
            }
        }

        int boxRowOffset = (i / 3) * 3;
        int boxColOffset = (j / 3) * 3;
        for (int k = 0; k < 3; ++k) // box
        {
            for (int m = 0; m < 3; ++m) {
                if (val == cells[boxRowOffset + k][boxColOffset + m]) {
                    return false;
                }
            }
        }

        return true;

    }

The most primitive sudoku is a 2x2 sudoku

1 2
2 1 

You have excaclty two solutions and every number is present in every row and every number is present in every column.

Another example is a 3x2

1 2
2 3
3 1

This is not solvable because not all numbers are present in every row.

Also a 9x6 will not have every number present in every row.

Therefore no solution is possible and this is not a sudoku.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM