2015-04-03 33 views
1

以下是我的解決方法。當我在我的主要方法中調用它時,沒有任何反應,並且所有的成功都不會執行,但eclipse沒有報告錯誤。Sudoku Backtracking

public boolean solve(int r, int c){ 
    if(c>8){ 
     c=0; 
     r++; 
    } 
    if(r>8){ 
     return true; 
    } 
    while(table[r][c].value!=0){ 
     c++; 
     if(c>8){ 
      c=-0; 
      r++; 
     } 
     if(r>8){ 
      return true; 
     } 
    } 
    for(int k=1;k<10;k++){ 
     if(table[r][c].checkRow(k)&&table[r][c].checkCol(k)&&table[r][c].checkCube(k)){ 
      table[r][c].value=k; 
      solve(r,c); 
     } 
    } 
    table[r][c].value=0; 
    return false; 
} 

該算法是否會回溯?如果不是,爲什麼?

回答

1

它看起來像一個邏輯錯誤,因此eclipse不報告任何東西。

在你的代碼迴路部分,你應該有這樣的事情

for(int k=1;k<10;k++){ 
     if(table[r][c].checkRow(k)&&table[r][c].checkCol(k)&&table[r][c].checkCube(k)){ 
      table[r][c].value=k; 
      if(solve(r,c)){ 
       return true; 
      } 
      table[r][c].value=0; 
     } 
    } 

在你的情況是未分配之外的表圈,防止代碼回溯。

Here是我解決sudoku的代碼。希望能幫助到你。