2016-05-18 5 views
0

私は、この再帰的なメソッドがユーザーが提供する単語と一致するときにtrueを返さない理由を突き止めようと壁に向かって頭を叩きました。単語の一致のためのJavaの再帰的メソッド

私はこのロジックを有する二次元アレイを作成してい:

charTest = letterString.toCharArray(); 

    char[][] twoDimCharArray = new char[][] 
      {{charTest[0],charTest[1],charTest[2],charTest[3]}, 
      {charTest[4],charTest[5],charTest[6],charTest[7]}, 
      {charTest[8],charTest[9],charTest[10],charTest[11]}, 
      {charTest[12],charTest[13],charTest[14],charTest[15]}}; 

ユーザ指定された文字列が期待して以下のメソッドに渡されることは、文字列の各文字を2次元アレイに対して検査し、見つかった場合隣接する位置には、mainメソッドからtrueを返します:

public boolean findWord(String word) { 
    for (int row = 0; row < this.board2.length; row++) { 
     for (int col = 0; col < this.board2.length; col++) { 
      if (this.findWord(word, row, col)) { 
       return true; 
      } 
     } 
    } 
    return false; 
} 

private boolean findWord(String word, int row, int col) { 
    if ( row < 0 || row >= this.board2.length || 
      col < 0 || col >= this.board2.length || 
      this.board2[row][col] != word.charAt(0)) { 
     return false; 
    } 
    else { 
     char safe = this.board2[row][col]; 
     this.board2[row][col] = '*'; 
     String rest = word.substring(1, word.length()); 
     Log.v("rest", rest + ""); 
     boolean result = this.findWord(rest, row-1, col-1) || 
       this.findWord(rest, row-1, col) || 
       this.findWord(rest, row-1, col+1) || 
       this.findWord(rest, row, col-1) || 
       this.findWord(rest, row, col+1) || 
       this.findWord(rest, row+1, col-1) || 
       this.findWord(rest, row+1, col) || 
       this.findWord(rest, row+1, col+1); 
     this.board2[row][col] = safe; 
     return result; 
    } 
} 

方法は関係なく、常に文字の位置のfalseを返しますが。私がデバッグしているとき、配列内のすべての位置を渡すように見えますが、最初の文字の一致を認識せず、2番目の文字のチェックを開始します。目立つものはどれも目立ちますか?

+1

私はthis.board2'が不適切再帰呼び出しの間で共有され、各ブランチは、それ自身のバージョンではなく、すでに近隣の支店によって台無しに1を持っているので、コピーする必要があります '推測すると思います。 – zapl

+0

これをデバッグするために何をしましたか?少なくとも、各ルーチンの上部と下部にあるprintステートメントを使用して、呼び出し側の引数を表示し、ステータスを返すようにします。これはおそらく問題を明らかにするでしょう。そうでない場合は、どこに見えるかを示すのに役立ちます。 – Prune

答えて

0

問題は、正の再帰終了のケースがないことです。 findWord()を改訂:

private boolean findWord(String word, int row, int col) { 

    if (row < 0 || row >= this.board2.length || 
     col < 0 || col >= this.board2.length || 
     this.board2[row][col] != word.charAt(0)) { 
     return false; 
    } 

    if (word.length() == 1) { 
     return true; 
    } 

    String rest = word.substring(1, word.length()); 

    char saved = this.board2[row][col]; 
    this.board2[row][col] = '*'; 

    boolean result = this.findWord(rest, row-1, col-1) || 
     this.findWord(rest, row-1, col) || 
     this.findWord(rest, row-1, col+1) || 
     this.findWord(rest, row, col-1) || 
     this.findWord(rest, row, col+1) || 
     this.findWord(rest, row+1, col-1) || 
     this.findWord(rest, row+1, col) || 
     this.findWord(rest, row+1, col+1); 

    this.board2[row][col] = saved; 

    return result; 
} 
関連する問題