2011-10-23 30 views
0

新手在這裏我已經編寫了一個代碼來搜索拼圖中的單詞,但單詞搜索在我運行該程序後似乎沒有返回任何內容。我將字典存儲在二叉樹中。我需要檢查每一個字符與我樹中的字符組合,請幫忙。謝謝....在謎題中搜索字詞

這是解決方法

public String solve() 
{ 
    int row = puzzle.length; 
    int coloumns = puzzle[0].length; 
    this.foundWords = new ArrayList<String>(); 
    if (this.dictionary == null) 
     return null; 
    for (int i = 0; i < this.puzzle[0].length; ++i) 
    { 
     for (int j = 0; j < this.puzzle.length; ++j) 
     { 
      if (this.getWord(i, j, 0, 1) == null) 
       continue; 
      if(this.inDictionary(this.getWord(i,j,0,1))) 
       this.foundWords.add(getWord(i,j,0,1).concat("\n" + this.mapDirection(0))); 
      for(int d = 0; d<8; ++d) 
      { 
       int n = 2; 
       String word = this.getWord(i,j,d,n); 
       while(word !=null) 
       { 
        if(this.inDictionary(word)) 
         this.foundWords.add(word.concat("\n" + this.mapDirection(d))); 
        word = this.getWord(i,j,d,n); 
        n++; 
       } 
      }    

     } 
    } 
    String temp = ""; 
    for(int i= 0; i < foundWords.size(); i++) 
    { 
     temp = temp.concat(foundWords.get(i)); 
    } 
    return temp; 
} 

這得到字..

public String getWord(int row, int column, int d, int length) 
{ 
    if (length < 1) 
     return null; 
    d %= 8; 

    StringBuilder rBuild = new StringBuilder(); 
    rBuild.append(this.puzzle[row][column]); 
    length--; 
    while (length >= 0) 
    { 
     if ((d == 3) || (d == 4) || (d == 5)) 
      column--; 
     if ((d == 1) || (d == 0) || (d == 7)) 
      column++; 

     if ((d == 1) || (d == 2) || (d == 3)) 
      row--; 
     if ((d == 5) || (d == 6) || (d == 7)) 
      row++; 

     if ((row < 0) || (row >= this.puzzle.length) 
     || (column < 0) || (column >= this.puzzle[0].length)) 
      return null; 

      rBuild.append(this.puzzle[row][column]); 
      length--; 
    } 

    return rBuild.toString(); 
} 

的方向..

public String mapDirection(int direction) 
{ 
    direction %=8; 
    switch(direction) 
    { 
     case 0: return " right"; 
     case 1: return " up and right"; 
     case 2: return " up"; 
     case 3: return " up and left"; 
     case 4: return " left"; 
     case 5: return " down and left"; 
     case 6: return " down and left"; 
     case 7: return " down and right"; 
    } 
    return null; 
} 
+0

當您瀏覽代碼時,您會看到什麼? –

+0

當我運行搜索,沒有任何反應,沒有例外,沒有字符串顯示什麼都沒有。如果我編輯temp並將其更​​改爲字符串,我會看到字符串,所以這告訴我foundWords似乎是空的。 – user938295

+1

開發環境是否不允許你逐行通過你的代碼?如果沒有,那麼添加一堆日誌記錄功能來查看它正在發生什麼以及它正在處理什麼。 –

回答

0

我認爲,在getWord中,該行:

while (length >= 0) 

應該

while (length > 0) 
+0

我試着得到了一個outOfBounds異常。 – user938295

+0

真的嗎?該更改應該減少循環中的次數。什麼行觸發OOB異常? –

+0

while(length> = 0) – user938295

1

你可以看看Jumble採取的方法,它實現here所示的第一算法。它比排列(第二)方法更快並且縮放更好。