I’m having a school project for Java and I’m assigned too. Now I’m having an issue with a part of the project which I can’t figure out.
The application must generate all possible word combinations (can be verified via a dictionary) from a two-dimensional char array (char[][] board). The board is dynamic as the user can choose the scale: 4×4, 5×5, 4×5, 5×4, 4×6, … So I guess a nested loop wouldn’t be approriate here, correct me if I’m wrong. Words must be generated horizontally, verticaly and diagonally. Example of a 4×4 board:
| u | a | u | s |
| n | n | i | i |
| a | o | e | b |
| e | u | e | z |
Code was completely wrong.
Another idea may be to brute force every possible path on the board and then try those saved paths to verify whether it’s a word or not.
Thanks in advance!
One way to solve this is:
To find all paths, you could adapt any graph traversal algorithm.
Now this will be really slow, because there are a great many paths of a board that size (for a board with n cells, we can have at most
n * 4 ^ (n - 1)paths, so for a 5 by 5 board, you’d have something like 25 * 2 ^ 50 ~= 10^16 paths.One way to improve on this is to interleave traversing the graph and checking the dictionary, aborting if the current path’s word is not a prefix of a dictionary word:
As you can see, the method walk invokes itself. This technique is known as recursion.
That leaves the matter of finding a data structure for the dictionary that supports efficient prefix queries. The best such data structure is a Trie. Alas, the JDK does not contain an implementation, but fortunately, writing one isn’t hard.
Note: The code in this answer has not been tested.