|
| 1 | +//Simple BFS solution |
| 2 | + |
| 3 | +classSolution { |
| 4 | +publicintopenLock(String[]deadends,Stringtarget) { |
| 5 | +Stringstart ="0000"; |
| 6 | +intans =0; |
| 7 | +Queue<String>q =newLinkedList<>(); |
| 8 | +HashSet<String>visited =newHashSet<>(); |
| 9 | +//Add all the deadends in the visited set so we can ignore them and visited values altogether. |
| 10 | +for (Strings:deadends) |
| 11 | +visited.add(s); |
| 12 | +q.offer(start); |
| 13 | +while (!q.isEmpty()) { |
| 14 | +intsize =q.size(); |
| 15 | +for (intj =0;j<size;j++) { |
| 16 | +Stringstr =q.poll(); |
| 17 | +StringBuildercur =newStringBuilder(str); |
| 18 | +if (str.equals(target))returnans; |
| 19 | +if (!visited.contains(cur.toString())) { |
| 20 | +for (inti =0;i<start.length();i++) { |
| 21 | +//edge case for 0 |
| 22 | +if (cur.charAt(i)=='0') { |
| 23 | +cur.setCharAt(i,'1'); |
| 24 | +q.offer(cur.toString()); |
| 25 | +cur.setCharAt(i,'9'); |
| 26 | +q.offer(cur.toString()); |
| 27 | + }elseif (cur.charAt(i)=='9') {//edge case for 9 |
| 28 | +cur.setCharAt(i,'0'); |
| 29 | +q.offer(cur.toString()); |
| 30 | +cur.setCharAt(i,'8'); |
| 31 | +q.offer(cur.toString()); |
| 32 | + }else { |
| 33 | +cur.setCharAt(i, ((char)(cur.charAt(i)+1))); |
| 34 | +q.offer(cur.toString()); |
| 35 | +cur.setCharAt(i, ((char)(cur.charAt(i)-2))); |
| 36 | +q.offer(cur.toString()); |
| 37 | + } |
| 38 | +visited.add(str); |
| 39 | +cur.setLength(0); |
| 40 | +cur.append(str); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | +ans++; |
| 45 | + } |
| 46 | +return -1; |
| 47 | + } |
| 48 | +} |