简体   繁体   English

数独解算器不更改值

[英]Sudoku solver not changing values

I am trying to implement a sudoku solver that works on any square sized board (4x4, 9x9, 16x6 etc.) This is what i currently have for my algorithm but once it runs no values end up being changed and theGrid is the same as before the solve was run. 我正在尝试实现一种可在任何方形板(4x4、9x9、16x6等)上运行的数独求解器。解决已运行。
I really don't know where it has gone wrong and any help is appreciated. 我真的不知道哪里出了问题,我们将不胜感激。

 private int[][] theGrid;
 private int emptyValue = -1;

 public int[][] solve() {
    recSolve(0, 0);
    return theGrid;
 }


 void recSolve(int i, int j) {
    int size = theGrid.length;
    if (i == size) {
        i = 0;
        if (++j == size)
            return;
            //done
    }
    if (theGrid[i][j] != emptyValue)  // skip filled cells
        recSolve(i+1,j);

    for (int val = 1; val <= size; ++val) {
        if (!isPresent(theGrid, i, j, val)) {
            theGrid[i][j] = val;
            recSolve(i+1,j)
        }
    }
    theGrid[i][j] = emptyValue; // reset on backtrack
}

 boolean isPresent(int[][] grid, int row, int col, int num){
    for(int i = 0; i < theGrid.length; i++){
        if(theGrid[i][col] == num) return false;
        if(theGrid[row][i] == num) return false;
    }
    int side = (int)Math.sqrt(theGrid.length);

    int rowStart = row - row % side;
    int colStart = col - col % side;

    for(int m = 0; m < side; m++){
        for(int k = 0; k < side; k++){
            if(grid[rowStart + k][colStart + m] == num) return false;
        }
    }
    return true;
}

I'd recommend running through a debugger and you'll soon see what's wrong. 我建议运行调试器,您很快就会发现问题所在。 As a start, isPresent returns true when the value is not present, which is the opposite of what I'd expect. 首先,当不存在该值时, isPresent返回true,这与我期望的相反。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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