Partially crrct using BFS on graph help someone


#1

int Solution::solve(string A, string B, vector &C) {
int flag1 = -1, flag2 = -1;
for(int i=0;i<C.size();i++){
if(C[i] == A)
flag1 = i;
if(C[i] == B)
flag2 = i;
if(flag1 != -1 && flag2 != -1)
break;
}
if(flag1==-1)
C.push_back(A);
if(flag2==-1)
C.push_back(B);
int n=C.size();
unordered_map<string,vector>adj;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(isValid(C[i],C[j])){
adj[C[i]].push_back(C[j]);
adj[C[j]].push_back(C[i]);
}
}
}
queueq;
unordered_map<string,int>mp;
q.push(A);
mp[A]=1;
while(!q.empty()){
string s=q.front();
q.pop();
for(string x:adj[s]){
if(mp[x]==0){
mp[x]=1+mp[s];
if(x==B)return mp[B];
q.push(x);
}
}
}
return 0;
}