Leetcode: Word ladder

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.