Leetcode_wordladder, leetcode
Description
Given two words (beginWord and endWord), and a dictionary, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
Start = "hit"
End = "cog"
Dict = ["hot", "dot", "dog", "lot", "log"]
As one shortest transformation is "hit"-"hot"-"dot"-"dog"-"cog ",
Return its length 5.
Problem solving Analysis
The general idea of this question is to give priority to BFS search, which can be performed by queue, but times out after several attempts:
- First, I use the relational matrix to represent the graph relationship. In this way, the complexity of N * N can also be seen in the analysis of TLE.
- Later, it was represented in the form of an adjacent table. It was noted that there are only 26 lower-case letters, and the question shows that the string length is the same, then the maximum number of edges is L * 26, the traversal and search of the adjacent table will soon start with N * L * 26, but the process of creating the adjacent table is still N * N, still TLE, try to find that the process of creating the big data adjacent table times out.
- In the end, we still use the idea of limited number of edges to generate reachable words from a word and determine whether the word is in the dictionary. In this way, we do not need to generate an adjacent table, here, because I used the shortlist for initial data processing, it was time-consuming to determine whether it was a candidate set, that is, the contain object. TLE finally used the set structure and finally ac.
- Review many knowledge points, BFS and queues, matrices and adjacent tables, java set and collection, java's queue interface is generally implemented by queue list
Code details
Public class Solution {public int ladderLength (String beginWord, String endWord, Set <String> wordDict) {wordDict. add (endWord); wordDict. add (endWord); Queue <NodeString> queue = new queue list <NodeString> (); Queue. add (new NodeString (beginWord, 1); wordDict. remove (beginWord); while (! Queue. isEmpty () {NodeString current = queue. poll (); if (current. string. equals (endWord) {return current. deep;} else {String tmp = current. string; // obtain the street-facing table from the vertex. Here, the maximum fixed number of variables are used for calculation, rather than using the matrix for (int I = 0; I <tmp. length (); I ++) {for (char c = 'a'; c <= 'Z'; c ++) {if (c = tmp. charAt (I) {continue;} else {char cc [] = tmp. toCharArray (); cc [I] = c; String s = new String (cc); if (wordDict. contains (s) {queue. add (new NodeString (s, current. deep + 1); wordDict. remove (s) ;}}}}} return 0;} class NodeString {String string; int deep; public NodeString (String string, int deep) {this. string = string; this. deep = deep ;}}}