【发布时间】:2020-10-26 10:03:53
【问题描述】:
我需要一些关于 BFS 词链作业的帮助。 单词链是基于五个字母的单词,当单词 x 的最后四个字母在单词 y 中时,两个单词被连接起来。例如爬升和飞艇是相连的,因为爬升中的 l、i、m 和 b 在 blimp 中。
建议使用 Sedgewick 算法第 4 版中的定向 BFS 或对其进行修改。代码可以在这里找到:https://algs4.cs.princeton.edu/40graphs/ 并使用以下代码阅读 列表单词的数据文件:
BufferedReader r =
new BufferedReader(new InputStreamReader(new FileInputStream(fnam)));
ArrayList<String> words = new ArrayList<String>();
while (true) {
String word = r.readLine();
if (word == null) { break; }
assert word.length() == 5; // inputcheck, if you run with assertions
words.add(word);
}
以及从文件中读取测试用例的以下代码:
BufferedReader r =
new BufferedReader(new InputStreamReader(new FileInputStream(fnam)));
while (true) {
String line = r.readLine();
if (line == null) { break; }
assert line.length() == 11; // inputcheck, if you run with assertions
String start = line.substring(0, 5);
String goal = line.substring(6, 11);
// ... search path from start to goal here
}
数据文件中的文字是:
their
moist
other
blimp
limps
about
there
pismo
abcde
bcdez
zcdea
bcdef
fzcde
当使用测试用例文件时...
other there
other their
their other
blimp moist
limps limps
moist limps
abcde zcdea
...输出应该是每个单词对之间的边数,如果单词之间没有路径,则输出-1。
1
1
-1
3
0
-1
2
我是使用图表的新手,我不确定如何使用 Sedgewick 的 BFS 并对其进行修改以读取测试用例文件。任何帮助表示赞赏。
【问题讨论】:
-
Java 是首选语言吗?还是单纯的算法无关紧要?
-
@DanielHao 我对其他语言不太熟悉,所以我更喜欢 Java,但即使是其他语言也可能会有所帮助。
-
你能发布你目前的代码吗?
-
只是为了理解,所以服务bfs算法,你不知道如何将文件传递给算法?对吗?
标签: java algorithm graph-algorithm