I have been trying to solve the 752th problem of LeetCode (Open the Lock) with BFS. Now, after polling from a queue, when I'm using the variable (type String) to equate it with the target String in an if condition, I am getting an NPE.
public int openLock(String[] deadends, String target) {
int len = target.length();
Set <String> s = new HashSet <String> (Arrays.asList(deadends));
Queue <String> q = new LinkedList <>();
q.add("0000");s.add("0000");
int cnt = 0;
while(!q.isEmpty()){
int size = q.size();
while(size>0){
String ans = q.poll(); String t="";
if(ans.equals(target))
return cnt;
if(s.contains(ans))
continue;
for(int i=len-1;i>=0;i--){
t=ans; char c = t.charAt(i);
if(c==target.charAt(i))
continue;
int act = c-'0';
int inc = (act+1)%10;
int dec = (act-1);
if(dec<0)
dec=dec+10;
t=t.substring(0,i)+inc+t.substring(i+1);
if(!s.contains(t)){
s.add(t);
q.add(t);
}
t=ans;
t=t.substring(0,i)+dec+t.substring(i+1);
if(!s.contains(t)){
s.add(t);
q.add(t);
}
}size--;
}
cnt++;
}
return -1;
}
}