Skip to content

Instantly share code, notes, and snippets.

@satveersm
Created July 10, 2017 16:55
Show Gist options
  • Save satveersm/95a7a9bbb04d5ec1c4305886c15892cd to your computer and use it in GitHub Desktop.
Save satveersm/95a7a9bbb04d5ec1c4305886c15892cd to your computer and use it in GitHub Desktop.
bool isChild(string str1, string str2)
{
if(str1.length() != str2.length())
return false;
int i = 0;
int count = 0;
while(i < str1.length())
{
if(str1[i] != str2[i])
{
count++;
}
}
return count == 1 ? true : false;
}
int Solution::ladderLength(string start, string end, vector<string> &dictV) {
std::deque<string> q;
q.push_back(start);
std::set<string> s;
s.insert(start);
int counter = 0;
bool found = false;
if(start.length() != end.length()) return 0;
while(!q.empty())
{
string str = q.front();
q.pop_front();
if(str == end)
{
found = true;
break;
}
for(int i = 0; i < dictV.size(); i++)
{
if(s.find(dictV[i]) == s.end() && isChild(str,dictV[i]))
{
q.push_back(dictV[i]);
s.insert(dictV[i]);
}
}
counter++;
}
if(found)
{
return counter;
}
else
{
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment