-1
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 板上工作,并且当我键入“完成”时,哈希集字典的输入会停止。

4

1 回答 1

1

我认为该算法没有任何问题,因此可能是输入数据使该算法不打印任何单词。我修改了代码以对输入数据进行硬编码,而不是从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

字典输入:bar,bars

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

于 2018-07-28T23:35:25.980 回答