File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ package task_1345 ;
2
+
3
+ import java .util .Map ;
4
+ import java .util .HashMap ;
5
+ import java .util .List ;
6
+ import java .util .Queue ;
7
+ import java .util .LinkedList ;
8
+ import java .util .ArrayList ;
9
+
10
+ public class Solution {
11
+
12
+ public int minJumps (int [] arr ) {
13
+ int n = arr .length ;
14
+ if (n == 1 ) {
15
+ return 0 ;
16
+ }
17
+ Map <Integer , List <Integer >> indices = new HashMap <>();
18
+ for (int i = 0 ; i < n ; i ++) {
19
+ indices .computeIfAbsent (arr [i ], k -> new ArrayList <>()).add (i );
20
+ }
21
+ Queue <Integer > storeIndex = new LinkedList <>();
22
+ boolean [] visited = new boolean [n ];
23
+ storeIndex .offer (0 );
24
+ visited [0 ] = true ;
25
+ int steps = 0 ;
26
+ while (!storeIndex .isEmpty ()) {
27
+ int size = storeIndex .size ();
28
+ while (size -- > 0 ) {
29
+ int currIndex = storeIndex .poll ();
30
+ if (currIndex == n - 1 ) {
31
+ return steps ;
32
+ }
33
+ List <Integer > jumpNextIndices = indices .get (arr [currIndex ]);
34
+ jumpNextIndices .add (currIndex - 1 );
35
+ jumpNextIndices .add (currIndex + 1 );
36
+ for (int jumpNextIndex : jumpNextIndices ) {
37
+ if (jumpNextIndex >= 0 && jumpNextIndex < n && !visited [jumpNextIndex ]) {
38
+ storeIndex .offer (jumpNextIndex );
39
+ visited [jumpNextIndex ] = true ;
40
+ }
41
+ }
42
+ jumpNextIndices .clear ();
43
+ }
44
+ steps ++;
45
+ }
46
+ return -1 ;
47
+ }
48
+
49
+ }
You can’t perform that action at this time.
0 commit comments