通过递归解决数独

时间:2014-03-19 18:45:16

标签: java recursion sudoku

我尝试编写递归来解决数独,并且我遇到了递归问题。 如果它无法解决它的确定,但是如果它可以解决则它会进入无限循环。

public static boolean recursion (int sodukuMatrix[][],int posRow, int posCol ,int i){

    if (posRow==0 && posCol==0 && i==10)
        return false;

    if(there is existing number){
        if (posCol==8 && posRow==8)
            return true;
        call recursion with next square
    }
    else {
        i=sodukuMatrix[posRow][posCol]+1;
        while (i<10){
            if (function: if I put i at the current location it is ok){
                sodukuMatrix[posRow][posCol]=i;        
                if (posCol==8 && posRow==8)
                    return true;
                call recursion with next square
            }
            else    
                i++;
        }
        sodukuMatrix[posRow][posCol]=0;
        return false;
    }
    return false;
}
}

1 个答案:

答案 0 :(得分:1)

在兔子洞里走一点。解决Sudoko似乎是Constraint-Satisfaction在类似于N-Queens Problem A MIN-CONFLICTS算法的上下文中的应用,可以与Simulated Annealing结合使用来找到最佳解决方案。

Peter Norvig's Artificial Intelligence a Modern Approach

考虑这个伪代码
function MIN-CONFLICTS(csp, max_steps) returns a solution or failure
  inputs: csp, a constraint satisfaction problem
  max_steps, the number of steps allowed before giving up

  current <- an initial complete assignment for csp
  for I = 1 to max_steps do
    if current is a solution for csp then return current
    var <- a randomly chosen conflicted variable from csp.VARIABLES
    value <- the value v for var that minimizes CONFLICTS(var, v, current, csp)
    set var = value in current
  return failure

在给定当前分配的其余部分的情况下,CONFLICTS函数计算特定值违反的约束数。

相关问题