Which algorithm would fit best to solve a word-search game like “Boggle” with Python

孤者浪人 提交于 2019-12-04 06:47:49

The basic algorithm is simple.

  • For each tile, do the following.
    • Start with an empty candidate word, then visit the current tile.
    • Visit a tile by following these steps.
      • Add the tile's position's letter to the candidate word.
      • Is the candidate word a known word? If so, add it to the found word list.
      • Is the candidate word a prefix to any known word?
        • If so, for each adjacent tile that has not been visited to form the candidate word, visit it (i.e., recurse).
        • If not, backtrack (stop considering new tiles for this candidate word).

To make things run smoothly when asking the question "is this word a prefix of any word in my dictionary", consider representing your dictionary as a trie. Tries offer fast lookup times for both words and prefixes.

You might find a Trie useful - put all dictionary words into a Trie, then make another Trie from the Boggle grid, only as long you're matching the dictionary Trie.

I.e. Dictionary trie:

S->T->A->C->K = stack
      \->R->K = stark
         \->T = start

Grid: (simplified)

STARKX 
XXXTXX 
XXXXXX

Grid trie: (only shown starting at S - also start at A for ART, etc)

S->X (no matches in dict Trie, so it stops) 
\->T->X
   \->A-R->K (match)
      | |->T (match)
      | \->X  
      \->C->K (match)
         \->X    

You could visualise your Tries with GraphViz like this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!