There're several solutions for it on stackoverflow, but none of them is ok (because they're looping for all possibilities).
My idea is probably wrong as well then: but here's an idea off the top of my head.
I wrote an algorithm which search through all possible combinations
If there are too many, then the problem is probably that you are also searching/looping through impossible combinations as well as possible combination.
For example when you place a word like "zro" in the top-left corner, there are very few "possible" combinations which can be placed in the vertical words below it:
- the first vertical word must begin with 'z'
- the second vertical word must begin with 'r'
- the third vertical word must begin with 'o'
- The combinations of letters on the second row (resulting from placing the vertical words) must itself be a valid word
- etc.
Therefore:
- Pick any word and place it in the top-left corner
- Find existing words which satisfy the constraints above
- If you find one or more such words, then continue in this way to see whether you can solve the whole thing; or if you fail, then try again using a different initial word
Summary:
- Don't generate every complete grid, and then test it to see whether it satisfies all constraints
- Instead use the constraints as you build the grid, to reduce the number of possibilities that you test
I'm suggesting that you solve the grid, starting from an initial word.
Instead of testing each words in the top-left corner, a better (e.g. because it moe quickly eliminates impossibilities) way to generate the starting position[s] is:
- Find the longest word (e.g.
rgfvacd
) - Find all possible combinations of words which cross/join it
- Try to place each of those valid combinations on the grid