-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path126.cpp
76 lines (72 loc) · 2.55 KB
/
126.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//
// 126.cpp
// leetcode
//
// Created by R Z on 2018/7/19.
// Copyright © 2018年 R Z. All rights reserved.
//
#include <stdio.h>
#include <vector>
#include <string>
#include <unordered_set>
#include <queue>
using namespace std;
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string> &wl) {
//very interesting problem
//It can be solved with standard BFS. The tricky idea is doing BFS of paths instead of words!
//Then the queue becomes a queue of paths.
unordered_set<string> wordList;
for(string s : wl) wordList.insert(s);
vector<vector<string>> ans;
queue<vector<string>> paths;
//wordList.insert(endWord);
paths.push({beginWord});
int level = 1;
int minLevel = INT_MAX;
//"visited" records all the visited nodes on this level
//these words will never be visited again after this level
//and should be removed from wordList. This is guaranteed
// by the shortest path.
unordered_set<string> visited;
while (!paths.empty()) {
vector<string> path = paths.front();
paths.pop();
if (path.size() > level) {
//reach a new level
for (string w : visited) wordList.erase(w);
visited.clear();
if (path.size() > minLevel)
break;
else
level = path.size();
}
string last = path.back();
//find next words in wordList by changing
//each element from 'a' to 'z'
for (int i = 0; i < last.size(); ++i) {
string news = last;
for (char c = 'a'; c <= 'z'; ++c) {
news[i] = c;
if (wordList.find(news) != wordList.end()) {
//next word is in wordList
//append this word to path
//path will be reused in the loop
//so copy a new path
vector<string> newpath = path;
newpath.push_back(news);
visited.insert(news);
if (news == endWord) {
minLevel = level;
ans.push_back(newpath);
}
else
paths.push(newpath);
}
}
}
}
return ans;
}
};