简体   繁体   English

使用 BFS 时,为什么我的单词没有在无向/未加权图中连接?

[英]Why aren't my Words connecting in Undirected/Unweighted Graph when using BFS?

Issue in my code, not sure why NO connections are found in the Graph built with the words.我的代码中出现问题,不确定为什么在用这些单词构建的图表中找不到任何连接。

ArrayList<String> words = new ArrayList<String>();
words.add("hello");
words.add("there");
words.add("here");
words.add("about");
                
Graph g = new Graph(words.size());
for(String word: words) {
  for(String word2: words){
       g.addEdge(words.indexOf(word), words.indexOf(word2));
  }
}

BufferedReader readValues = 
    new BufferedReader(new InputStreamReader(new FileInputStream("values.txt")));

while(true)
{
    String line = readTestFile.readLine();
    if (line == null) { break; }
    assert line.length() == 11; 
    String start = line.substring(0, 5);
    String goal = line.substring(6, 11);
            
    BreadthFirstPaths bfs = new BreadthFirstPaths(g, words.indexOf(start));
    if (bfs.hasPathTo(words.indexOf(goal))) {
    System.out.println(bfs.distTo(words.indexOf(goal)));
     for (int v : bfs.pathTo(words.indexOf(goal))) {
               System.out.println(v);
     }
    }
    else System.out.println("Nothing");
}

Contents of the Text file:文本文件的内容:

hello there
hello here
about here

I seem to get:我似乎得到:

Nothing
Nothing
Nothing
Nothing
Nothing 

Not sure of why?不知道为什么?

EDIT: OP seems to have trouble with the code here, especially, the graph.编辑: OP 似乎对这里的代码有问题,尤其是图表。 I do not know specifically why, but, I am sure there are those who do.我不知道具体为什么,但是,我相信有些人会这样做。

I suppose you are using the source code from the excellent book from Robert Sedgewick and Kevin Wayne about algorithms implementation in Java Algorithms, 4th Edition .我想您正在使用来自 Robert Sedgewick 和 Kevin Wayne 的关于 Java Algorithms, 4th Edition中算法实现的优秀书籍的源代码。

There is no reason why your code should not work fine.您的代码没有理由不能正常工作。 Please, consider the following test based on your code:请根据您的代码考虑以下测试:

public static void main(String... args) throws IOException {
  ArrayList<String> words = new ArrayList<String>();
  words.add("hello");
  words.add("there");
  words.add("here");
  words.add("about");

  Graph g = new Graph(words.size());
  for(String word: words) {
    for(String word2: words){
      g.addEdge(words.indexOf(word), words.indexOf(word2));
    }
  }

  BufferedReader readValues = null;

  try {

    readValues =
        new BufferedReader(new InputStreamReader(new FileInputStream("values.txt")));

    String line = null;
    while ((line = readValues.readLine()) != null) {
      // assert line.length() == 11;
      String[] tokens = line.split(" ");
      String start = tokens[0];
      String goal = tokens[1];

      BreadthFirstPaths bfs = new BreadthFirstPaths(g, words.indexOf(start));
      if (bfs.hasPathTo(words.indexOf(goal))) {
        System.out.println("Shortest path distance from " + start + " to " + goal + " = " + bfs.distTo(words.indexOf(goal)));
        StringBuilder path = new StringBuilder();
        String sep = "";
        for (int v : bfs.pathTo(words.indexOf(goal))) {
          path.append(sep).append(v);
          sep = " -> ";
        }

        System.out.println("Shortest path = " + path.toString());
      } else System.out.println("Nothing");
    }

  } finally {
    if (readValues != null) {
      try {
        readValues.close();
      } catch (Throwable t) {
        t.printStackTrace();
      }
    }
  }
}

If you run this program with the text file that you indicated it will produce an output similar to the following:如果您使用您指示的文本文件运行此程序,它将产生类似于以下内容的 output:

Shortest path distance from hello to there = 1
Shortest path = 0 -> 1
Shortest path distance from hello to here = 1
Shortest path = 0 -> 2
Shortest path distance from about to here = 1
Shortest path = 3 -> 2

The main change I introduced is the code related with the calculation of the start and goal variables:我介绍的主要变化是与startgoal变量的计算相关的代码:

String[] tokens = line.split(" ");
String start = tokens[0];
String goal = tokens[1];

I assume you are using another text file, perhaps another code;我假设您正在使用另一个文本文件,也许是另一个代码; with the one provided the assertion will fail or a StringIndexOutOfBounds exception will be raised when you calculate goal as the substring from index 6 to 11 .如果您将goal计算为从索引611substring ,则断言将失败或引发StringIndexOutOfBounds异常。

Apart from that, the algorithm should work fine.除此之外,该算法应该可以正常工作。

That being said, please, be aware that you are constructing a graph hyperconnected , in which every node has a direct path to a different node and itself.话虽如此,请注意您正在构建一个图hyperconnected ,其中每个节点都有到不同节点及其自身的直接路径。 Maybe that could be your objective, but be aware that things get interesting when you do some other kind of stuff.也许这可能是您的目标,但请注意,当您做一些其他类型的事情时,事情会变得有趣。

For instance, if instead of this code:例如,如果不是此代码:

for(String word: words) {
  for(String word2: words){
    g.addEdge(words.indexOf(word), words.indexOf(word2));
  }
}

You try something like this:你尝试这样的事情:

g.addEdge(words.indexOf("hello"), words.indexOf("there"));
g.addEdge(words.indexOf("hello"), words.indexOf("about"));
g.addEdge(words.indexOf("about"), words.indexOf("here"));

The output of the algorithm has more sense:算法的output更有意义:

Shortest path distance from hello to there = 1
Shortest path = 0 -> 1
Shortest path distance from hello to here = 2
Shortest path = 0 -> 3 -> 2
Shortest path distance from about to here = 1
Shortest path = 3 -> 2

I suppose you are using code from Java Textbook我想您正在使用Java 教科书中的代码

your code should be你的代码应该是

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;


public class words_sof {

    public static void main(String[] args) throws IOException {

        ArrayList<String> words = new ArrayList<String>();
        words.add("hello");
        words.add("there");
        words.add("here");
        words.add("about");

        Graph g = new Graph(words.size());
        for (String word : words) {
            for (String word2 : words) {
                g.addEdge(words.indexOf(word), words.indexOf(word2));
            }
        }

        try (BufferedReader readValues = new BufferedReader(new InputStreamReader(new FileInputStream("values.txt")))) {

            while (true) {
// ORIGINAL     String line = readTestFile.readLine();
// Should be
                String line = readValues.readLine();
                if (line == null) {
                    break;
                }
                
// ORIGINAL parse like this is not appropriate              
//              assert line.length() == 11;
//              String start = line.substring(0, 5);
//              String goal = line.substring(6, 11);
                // Use something like https://stackoverflow.com/questions/20728050/split-strings-in-java-by-words
                 String [] tokens = line.split("[\\s']");
                 
                 String start = tokens[0];
                 String goal = tokens[1];
                 
                BreadthFirstPaths bfs = new BreadthFirstPaths(g, words.indexOf(start));
                if (bfs.hasPathTo(words.indexOf(goal))) {
// Captions added for clarity                   
                    System.out.println("Distance : " + bfs.distTo(words.indexOf(goal)));
                    for (int v : bfs.pathTo(words.indexOf(goal))) {
                        System.out.print(" -> " + v);
                    }
                    System.out.println();
                } else
                    System.out.println("Nothing");
            }
        }
    }

}

Please notice modifications to the请注意修改

// ORIGINAL lines. // 原始行。

The code above yields上面的代码产生

Distance : 1
 -> 0 -> 1
Distance : 1
 -> 0 -> 2
Distance : 1
 -> 3 -> 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM