Question:
Https://oj.leetcode.com/problems/word-ladder/
Analysis:
1. Find the shortest path and use the BFS algorithm. [3]
2. Find the adjacent relationship between words, and do not use the adjacent matrix. Otherwise, the time limit exceeded will occur. [2]
Because not all words need to be adjacent to each other, you only need to solve the neighbors of some words used. It takes a lot of time to obtain the adjacent matrix.
3. After a word is accessed, it can be directly deleted from dict to avoid repeated addition to the queue, resulting in a waste of time. [1]
4. You can create a new depth queue to record the path length. In this way, when the que queue is pushed, the depth queue also pushes a corresponding path at the same time. [1]
Code:
class Solution{public:int ladderLength(string start, string end, unordered_set<string> &dict){dict.insert(end);queue<string> que;queue<int> depth;que.push(start);depth.push(2);int len;while (!que.empty()){string ver = que.front();que.pop();len = depth.front();depth.pop();vector<string> res;adjacency(ver, dict, res);for (auto &r : res){if (r == end)return len;else{dict.erase(r);que.push(r);depth.push(len+1);}}}return 0;};void adjacency(const string &ver, const unordered_set<string> &dict, vector<string> &res){for (int i = 0; i < ver.size(); i++){string temp = ver;for (int j = 'a'; j <= 'z'; j++){temp[i] = j;if (temp != ver && dict.find(temp) != dict.end())res.push_back(temp);}}return;}};
Refer:
[1] http://blog.csdn.net/lanxu_yy/article/details/17588317
[2] http://blog.csdn.net/yutianzuijin/article/details/12887747
[3] data structure (C ++ language edition) (Third edition) Deng Junhui p169
Leetcode: Word ladder