functionbfs(g) { // q uses to save nodes in current level. let q = [g.start], level = 0; while (q.length) { const nq = []; for (const val of q) { if (val == g.end) return level; for (const next of val.children) { nq.push(next); } } q = nq; level++; } return0; }
var ladderLength = function(bw, ew, wl) { wl = newSet(wl); if (!wl.has(ew)) return0; // start set and end set. let ss = newSet([bw]), es = newSet([ew]); let level = 1; while (ss.size) { // new start set const nss = newSet(); // each word in ss for (const k of ss) { // find if the word changes a char can get an exist word. // iterate through different index and different replace char. for (let i = 0; i < k.length; i++) { for (let j = 0; j < 26; j++) { const ch = String.fromCharCode(97 + j); if (ch != k[i]) { // generate new string. const ns = k.slice(0, i) + ch + k.slice(i + 1); // find the end, return. if (es.has(ns)) { return level + 1; } // the next word exist, add to new start set. if (wl.has(ns)) { nss.add(ns); wl.delete(ns); } } } } } level++; ss = nss; // select smaller set as start set. **!important** if (ss.size > es.size) { [ss, es] = [es, ss]; } } return0; };