File tree 1 file changed +41
-0
lines changed 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int openLock (String [] deadends , String target ) {
3
+ Set <String > deadEndSet = new HashSet <>(Arrays .asList (deadends ));
4
+ if (deadEndSet .contains (target ) || deadEndSet .contains ("0000" )) {
5
+ return -1 ;
6
+ }
7
+ Queue <String > queue = new LinkedList <>();
8
+ Set <String > seen = new HashSet <>();
9
+ queue .add ("0000" );
10
+ seen .add ("0000" );
11
+ int steps = 0 ;
12
+ int [] rotations = {-1 , 1 };
13
+ while (!queue .isEmpty ()) {
14
+ int size = queue .size ();
15
+ for (int i = 0 ; i < size ; i ++) {
16
+ String removed = queue .remove ();
17
+ if (removed .equals (target )) {
18
+ return steps ;
19
+ }
20
+ if (deadEndSet .contains (removed )) {
21
+ continue ;
22
+ }
23
+ for (int j = 0 ; j < 4 ; j ++) {
24
+ for (int rotation : rotations ) {
25
+ int changedVal = ((removed .charAt (j ) - '0' ) + rotation + 10 ) % 10 ;
26
+ String newRotation = new StringBuilder ()
27
+ .append (removed .substring (0 ,j )) .append (changedVal )
28
+ .append (removed .substring (j + 1 ))
29
+ .toString ();
30
+ if (!seen .contains (newRotation )) {
31
+ seen .add (newRotation );
32
+ queue .add (newRotation );
33
+ }
34
+ }
35
+ }
36
+ }
37
+ steps ++;
38
+ }
39
+ return -1 ;
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments