I implement the BFS using a queue. It always hit the TLE exception. Please help pointing out my mistake.

(Last executed input: "sand", "acne", ["slit","bunk",....)

Thanks so much.

Code:

```
public int ladderLength(String start, String end, HashSet<String> dict) {
//building a graph
dict.add(start);
dict.add(end);
int n = dict.size();
//the graph consisting nodes array
Node[] nodes= new Node[n];
Iterator itr = dict.iterator();
Node startNode=null, endNode=null;
//create node for each dict word
for (int i = 0; i < n; i++) {
Node nd = new Node();
nd.data = (String)itr.next();
nodes[i] = nd;
//set start and end
if(nd.data.equals(start))
startNode = nd;
if(nd.data.equals(end))
endNode = nd;
}
//O(n-square)
//find neighbors of each node
for (int i = 0; i < n; i++) {
Node current = nodes[i];
current.neighbor = neighbor(current,nodes);
}
//BFS implemented by a Queue
Queue<Node> aQ = new LinkedList<Node>();
aQ.add(startNode);
int counter = 1;
while(!aQ.isEmpty()){ //O(n-square) n is the # of edge
Node pointer = (Node)aQ.poll();
mark(pointer);
if(pointer==endNode){
return pointer.distance;
}
Iterator<Node> neiItr = pointer.neighbor.iterator();
while (neiItr.hasNext()) {
Node current = (Node)neiItr.next();
if(current.visited==false){
aQ.add(current);
current.distance = ++counter;
}
}
}
return 0;
}
public void mark(Node t){
t.visited=true;
}
public void markAll(ArrayList<Node> t){
Iterator itr = t.iterator();
while(itr.hasNext()){
((Node)itr.next()).visited=true;
}
}
public ArrayList<Node> neighbor(Node nd, Node[] nodes){
ArrayList<Node> neighors = new ArrayList<Node>();
for (int i = 0; i < nodes.length; i++) {
Node current = nodes[i];
if(current.isNeighborOf(nd))
neighors.add(current);
}
return neighors;
}
class Node{
String data;
int distance = 0;
boolean visited = false;
ArrayList<Node> neighbor;
/**
* O(n)
* @param t
* @return
*/
public boolean isNeighborOf(Node t){
int ctr = 0;
for (int i = 0; i < data.length(); i++) {
if(data.charAt(i)!=t.data.charAt(i)){
ctr++;
if(ctr>1)
return false;
}
}
//ctr has to be bigger than 1
//set is non duplicate
return true;
}
}
```