为什么我的Java Boggle代码不起作用


public class coggle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
HashSet<String> d = new HashSet<>();
String[][] board = new String[5][5];
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
board[i][j] = scan.next();
}
scan.nextLine();
}
String next = "";
while (scan.hasNextLine()) {
next = scan.nextLine();
if ("done".equals(next)) {
break;
}
d.add(next);
}
boolean[][] visited = new boolean[5][5];
ArrayList<String> s = new ArrayList<>();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
f(i, j, board, visited, "", d, s);
}
}  
}
public static void f(int r, int c, String[][] board, boolean[][] visited, String s, HashSet<String> d, ArrayList<String> words) {
if (r >= 5 || r < 0) {
return;
}if (c >= 5 || c < 0) {
return;
}if (visited[r][c]) {
return;
}
s += board[r][c];
if (d.contains(s) && !words.contains(s)) {
words.add(s);
System.out.println(s);
}
visited[r][c] = true;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
f(r + i, c + j, board, visited, s, d, words);
}
}
}
}

基本上,我只想让程序打印出找到的任何单词。然而,它从不印刷任何文字。

它应该在5x5板上工作,当我键入"done"时,hashset字典的输入就会停止。

我没有发现算法有任何问题,所以可能是输入数据导致算法不打印任何单词。我修改了代码,对输入数据进行硬编码,而不是从System.in中检索。

板输入:

b | a | r | s | z
z | z | z | z | z
z | z | z | z | z
z | z | z | z | z
z | z | z | z | z

字典输入:barbars

public class Coogle {
public static void main(String[] args) {
HashSet<String> d = new HashSet<>(Arrays.asList("bar", "bars"));
String[][] board = {{"b", "a", "r", "s", "z"}, {"z", "z", "z", "z", "z"}, {"z", "z", "z", "z", "z"}, {"z", "z", "z", "z", "z"}, {"z", "z", "z", "z", "z"}};
boolean[][] visited = new boolean[5][5];
ArrayList<String> s = new ArrayList<>();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
f(i, j, board, visited, "", d, s);
}
}
}
public static void f(int r, int c, String[][] board, boolean[][] visited, String s, HashSet<String> d, ArrayList<String> words) {
if (r >= 5 || r < 0) {
return;
}
if (c >= 5 || c < 0) {
return;
}
if (visited[r][c]) {
return;
}
s += board[r][c];
if (d.contains(s) && !words.contains(s)) {
words.add(s);
System.out.println(s);
}
visited[r][c] = true;
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
f(r + i, c + j, board, visited, s, d, words);
}
}
}
}

算法是打印barbars

相关内容

  • 没有找到相关文章

最新更新