用bfs搜索

时间:2011-08-14 02:28:46

标签: java hashset wordnet breadth-first-search

我从wordnet检索同义词并将其作为数组返回。这是我的代码的一部分

<pre>
RiWordnet wordnet = new RiWordnet();
String word = lineTF.getText();
// Get synsets
String[] synsets = wordnet.getAllSynsets(word, "n");
String outputSynset = "Word: " + word;

    GUIsynonymTA.append("\n");
    GUIsynonymTA.append(outputSynset);
    GUIsynonymTA.append("\n");

    if (synsets != null) 
    {

    for (int i = 0; i < synsets.length; i++) 
    {
    GUIsynonymTA.append("\n");
    GUIsynonymTA.append("Synsets " + i + ": " + (synsets[i]));                        
    GUIsynonymTA.append("\n");

    //implement BFS here
<code>

直到这一行,我已成功检索到同义词。我要做的是在搜索WordNet同义词时实现广度优先搜索。我从RiWordnet库调用方法getAllSynsets,它存储了wordnet中的所有同义词。我尝试使用循环(if..else),但我不知道在哪里停止搜索。使用BFS应该知道搜索的范围,其中搜索同义词被标记为被访问的节点。这是一个我想在搜索同义词时使用BFS实现的概念。

例如:

student = {pupil, educatee, scholar, bookman} 

pupil = {student, educatee, schoolchild}

educatee = {student, pupil} --> has been search, so go to the next synonym.

schoolchild = {pupil} --> has been search, so go to the next synonym.

scholar = {bookman, student, learner, assimilator}

bookman = {scholar, student} --> has been search, so go to the next synonym.

learner = {scholar, assimilator, apprentice, prentice}

assimilator = {learner, scholar} --> has been search, so go to the next synonym.

apprentice = {learner} --> has been search, so go to the next synonym.

prentice = {apprentice, learner} --> has been search, so go to the next synonym.

ALL SYNONYM HAS BEEN SEARCH, SO STOP. 

有些人还建议我应用HashSet而不是BFS。谁能帮我?提前谢谢..

1 个答案:

答案 0 :(得分:0)

听起来你想要这样的东西:

Queue<String> pending = ...
HashSet<String> processed = ...

pending.add("startWord"); 
processed.add("startWord");

while (!pending.isEmpty()) {
   String word = pending.remove();

   String[] possibilities = wordnet.getAllSynsets(word, "n");
   for (String p : possibilities) {
     // Make sure we haven't already processed the new word 
     if (!processed.contains(p)) {
        pending.add(p);
        processed.contains(p);
      }
   }
}

//  At this point, processed contains all synonyms found

这或多或少是同义词的递归扩展(基本上就是BFS)。