Shortest path to transform one word into another

后端 未结 9 2373
梦如初夏
梦如初夏 2020-12-01 00:44

For a Data Structures project, I must find the shortest path between two words (like \"cat\" and \"dog\"), changing only one letter at a time. We a

9条回答
  •  盖世英雄少女心
    2020-12-01 01:02

    There are methods of varying efficiency for finding links - you can construct a complete graph for each word length, or you can construct a BK-Tree, for example, but your friend is right - BFS is the most efficient algorithm.

    There is, however, a way to significantly improve your runtime: Instead of doing a single BFS from the source node, do two breadth first searches, starting at either end of the graph, and terminating when you find a common node in their frontier sets. The amount of work you have to do is roughly half what is required if you search from only one end.

提交回复
热议问题