Why am i getting TLE with below code


#1

int Solution::solve(string a, string b, vector &c) {
queueq;
q.push(a);
if(a.compare(b)==0)return 0;

unordered_set<string>dic(c.begin(), c.end());

if(dic.find(b)==dic.end())return 0;

unordered_map<string,int> rel;
rel[a]=1;
while(!q.empty()){
    string n=q.front();
    q.pop();
    for(int i=0;i<n.size();i++){
     
     
     
     for(int j=0;j<26;j++){
        string t=n;
        t[i]='a'+j;
                        if(t.compare(b)==0)return rel[n]+1;

        
        if(dic.find(t)!=dic.end()){
        if(rel.find(t)==rel.end()){
            q.push(t);
            rel[t]=rel[n]+1;
            
            //mp.insert(t);
           // break;
            
        }    
            
            
            
        }
    }
     
    }
    
    
    
    
}
return 0;

}


#2

just try to not use extra unordered_map. You can directly erase from dic. I was having same kind of problem, but solved after changing those . Your code is very much similar with mine. Just compare it at once.

int Solution::solve(string A, string B, vector &C) {
set st;
for(int i=0;i<C.size();i++)
st.insert(C[i]);
if(st.find(B)==st.end())return 0;
queue<pair<string,int>> q;
q.push({A,1});
int move=1;
while(!q.empty()){
string s=q.front().first;
move=q.front().second;
string temp=s;
if(s==B)return move;
q.pop();
for(int i=0;i<s.length();i++)
{
for(char j=ā€˜aā€™;j<=ā€˜zā€™;j++)
{
s[i]=j;
if(s==B)return move+1;
if(s==temp)continue;
if(st.find(s)!=st.end()){
q.push({s,move+1});
st.erase(s);
}
}
s=temp;
}
}
return 0;
}