Advertisement
Guest User

Grokking 230

a guest
Aug 11th, 2022
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. class Solution {
  2.  
  3. final static int[][] DIRS = {{2, 1}, {-2, -1}, {2, -1}, {-2, 1},
  4. {1, 2}, {-1, -2}, {1, -2}, {-1, 2}};
  5. final static int OFFSET = 302;
  6.  
  7. public int minKnightMoves(int x, int y) {
  8. boolean[][] visited = new boolean[OFFSET * 2 + 1][OFFSET * 2 + 1];
  9.  
  10. Queue<int[]> queue = new LinkedList<>();
  11. queue.offer(new int[] {0, 0});
  12. visited[OFFSET][OFFSET] = true;
  13. int steps = 0;
  14.  
  15. while (!queue.isEmpty()) {
  16. int qSize = queue.size();
  17.  
  18. for (int i = 0; i < qSize; i++) {
  19. int[] at = queue.poll();
  20. if (at[0] == x && at[1] == y) {
  21. return steps;
  22. }
  23.  
  24. for (int[] dir : DIRS) {
  25. int rr = at[0] + dir[0];
  26. int cc = at[1] + dir[1];
  27.  
  28. if (!visited[OFFSET + rr][OFFSET + cc]) {
  29. visited[OFFSET + rr][OFFSET + cc] = true;
  30. queue.offer(new int[] {rr, cc});
  31. }
  32. }
  33. }
  34. steps++;
  35. }
  36.  
  37. return 0; // unreachable code
  38. }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement