2014-03-19 53 views
0

我试着写递归来解决数独,并且我遇到了递归问题。 如果它无法解决的话,但是如果它可以解决的话,它会进入无限循环。通过递归求解数独

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

听起来像你有一个*编译*代码的版本。这样做会使这个更容易理解。 – femtoRgon

+0

我仍然是新手在编程,所以我真的不知道该怎么做(或者你的意思是什么..)。谢谢 –

+0

你发布的代码不*进入无限循环,因为它不是有效的java。它不能编译,所以你根本无法执行它。这里有句法错误:'if(rec(cloneMatrix,sodukuMatrix,posRow,posCol + 1,i))}',显然,在'if(function:如果我把i放在当前位置就可以){ '。 – femtoRgon

回答

1

去兔子洞一点点。解决Sudoko看起来像Constraint-Satisfaction在类似于N-Queens Problem的上下文中的应用可以使用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 

冲突函数计算通过一个特定的值违反约束的数量伪代码,鉴于当前分配的其余部分。

+0

感谢您的详细解答 –