-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathWordLadderII.cpp
109 lines (86 loc) · 2.27 KB
/
WordLadderII.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
/*
Given two words (start and end), and a dictionary, find the shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
If there are multiple such sequence of shortest length, return all of them. Refer to the example for more details.
Example :
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
Note:
All words have the same length.
All words contain only lowercase alphabetic characters.
LINK: https://www.interviewbit.com/problems/word-ladder-ii/
*/
vector<vector<string> > res;
int nd, minL;
string en;
bool isAdj(string a, string b)
{
int n = a.length();
int cnt = 0;
for(int i=0;i<n;i++)
{
if(a[i]!=b[i])
cnt++;
if(cnt>1)
return false;
}
return cnt==1? true : false;
}
void dfs(vector<string> &dict, vector<string> &temp, bool vis[], int len)
{
if(len>minL)
return;
if(temp[len-1] == en)
{
if(minL > len)
{
minL = len;
res.clear();
}
res.push_back(temp);
return;
}
string s = temp[len-1];
for(int i=0;i<nd;i++)
{
if(vis[i] == false && isAdj(s,dict[i]))
{
vis[i] = true;
temp.push_back(dict[i]);
dfs(dict,temp,vis,len+1);
temp.pop_back();
vis[i] = false;
}
}
}
vector<vector<string> > Solution::findLadders(string start, string end, vector<string> &dict)
{
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
res.clear();
dict.push_back(end);
unordered_set<string> st;
for(auto x : dict)
st.insert(x);
dict.assign(st.begin(), st.end());
sort(dict.begin(), dict.end());
nd = dict.size();
minL = INT_MAX;
en = end;
vector<string> temp;
bool vis[nd];
memset(vis,false,sizeof(vis));
temp.push_back(start);
dfs(dict,temp,vis,1);
return res;
}