Skip to content

Instantly share code, notes, and snippets.

@vipul43
Created February 17, 2021 17:11
Show Gist options
  • Save vipul43/f097da76b178d13db2c717d9fb8361a0 to your computer and use it in GitHub Desktop.
Save vipul43/f097da76b178d13db2c717d9fb8361a0 to your computer and use it in GitHub Desktop.
16th feb, 2021; favourite problem of the day; problem link: https://www.interviewbit.com/problems/word-ladder-i/
bool differByOneChar(string &a, string &b){
int diff = 0;
for(int i=0; i<a.size(); ++i){
if(a[i]!=b[i]) diff++;
if(diff>1) return false;
}
return diff==1;
}
int dfsHelper(unordered_map<string, vector<string>> &adj, string A, string B){
queue<string> s;
unordered_map<string, int> vis;
s.push(A);
int minDist = 0;
while(!s.empty()){
int size = s.size();
while(size--){
string temp = s.front(); s.pop();
vis[temp]=1;
if(temp==B){
return minDist+1;
}
for(string v:adj[temp]){
if(vis[v]==0){
s.push(v);
}
}
}
minDist++;
}
return 0;
}
int Solution::solve(string A, string B, vector<string> &C) {
C.push_back(A);
C.push_back(B);
unordered_map<string, vector<string>> adj;
for(int i=0; i<C.size()-1; ++i){
for(int j=i+1; j<C.size(); ++j){
bool res = differByOneChar(C[i], C[j]);
if(res){
adj[C[i]].push_back(C[j]);
adj[C[j]].push_back(C[i]);
}
}
}
return dfsHelper(adj, A, B);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment