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);
}
}
}
}
Basically, I just want the program to print out any words that are found. It never prints any words, however.
It is supposed to work on a 5x5 board, and and the input for the hashset dictionary stops when I type "done".
I don't see anything wrong with the algorithm so it may be the input data that is making the algorithm not to print any word. I modified the code to hard code the input data instead of retrieving it from
System.in
.Board input:
Dictionary input:
bar
,bars
The algorithm is printing
bar
andbars