File tree Expand file tree Collapse file tree 3 files changed +512
-428
lines changed
paginated_contents/algorithms/2nd_thousand
main/java/com/fishercoder/solutions/secondthousand
test/java/com/fishercoder/secondthousand Expand file tree Collapse file tree 3 files changed +512
-428
lines changed Load Diff Large diffs are not rendered by default.
Original file line number Diff line number Diff line change
1
+ package com .fishercoder .solutions .secondthousand ;
2
+
3
+ import java .util .HashSet ;
4
+ import java .util .LinkedList ;
5
+ import java .util .Queue ;
6
+ import java .util .Set ;
7
+
8
+ public class _1197 {
9
+ public static class Solution1 {
10
+ /**
11
+ * My completely original solution.
12
+ */
13
+ public int minKnightMoves (int x , int y ) {
14
+ int boundary = 600 ;//this is from the constraints of this problem: -300 <= x, y <= 300
15
+ Queue <int []> q = new LinkedList <>();
16
+ q .offer (new int []{0 , 0 });
17
+ int moves = 0 ;
18
+ int [][] dirs = new int [][]{
19
+ {-2 , 1 },
20
+ {-1 , 2 },
21
+ {1 , 2 },
22
+ {2 , 1 },
23
+ {2 , -1 },
24
+ {1 , -2 },
25
+ {-1 , -2 },
26
+ {-2 , -1 }
27
+ };
28
+ Set <Integer > visited = new HashSet <>();
29
+ visited .add (0 );
30
+ while (!q .isEmpty ()) {
31
+ int size = q .size ();
32
+ for (int i = 0 ; i < size ; i ++) {
33
+ int [] curr = q .poll ();
34
+ if (curr [0 ] == x && curr [1 ] == y ) {
35
+ return moves ;
36
+ }
37
+ for (int [] dir : dirs ) {
38
+ int nextx = dir [0 ] + curr [0 ];
39
+ int nexty = dir [1 ] + curr [1 ];
40
+ if (visited .add (nexty * boundary + nextx )) {
41
+ //formula: col * size of matrix + row, is a common way to project a 2D matrix onto 1D array
42
+ q .offer (new int []{nextx , nexty });
43
+ }
44
+ }
45
+ }
46
+ moves ++;
47
+ }
48
+ return moves ;
49
+ }
50
+ }
51
+ }
Original file line number Diff line number Diff line change
1
+ package com .fishercoder .secondthousand ;
2
+
3
+ import com .fishercoder .solutions .secondthousand ._1197 ;
4
+ import org .junit .jupiter .api .BeforeEach ;
5
+ import org .junit .jupiter .api .Test ;
6
+
7
+ import static org .junit .jupiter .api .Assertions .assertEquals ;
8
+
9
+ public class _1197Test {
10
+ private static _1197 .Solution1 solution1 ;
11
+
12
+ @ BeforeEach
13
+ public void setup () {
14
+ solution1 = new _1197 .Solution1 ();
15
+ }
16
+
17
+ @ Test
18
+ public void test1 () {
19
+ assertEquals (1 , solution1 .minKnightMoves (2 , 1 ));
20
+ }
21
+
22
+ @ Test
23
+ public void test2 () {
24
+ assertEquals (4 , solution1 .minKnightMoves (5 , 5 ));
25
+ }
26
+
27
+ @ Test
28
+ public void test3 () {
29
+ assertEquals (56 , solution1 .minKnightMoves (2 , 112 ));
30
+ }
31
+
32
+ }
You can’t perform that action at this time.
0 commit comments