Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- final static int[][] DIRS = {{2, 1}, {-2, -1}, {2, -1}, {-2, 1},
- {1, 2}, {-1, -2}, {1, -2}, {-1, 2}};
- final static int OFFSET = 302;
- public int minKnightMoves(int x, int y) {
- boolean[][] visited = new boolean[OFFSET * 2 + 1][OFFSET * 2 + 1];
- Queue<int[]> queue = new LinkedList<>();
- queue.offer(new int[] {0, 0});
- visited[OFFSET][OFFSET] = true;
- int steps = 0;
- while (!queue.isEmpty()) {
- int qSize = queue.size();
- for (int i = 0; i < qSize; i++) {
- int[] at = queue.poll();
- if (at[0] == x && at[1] == y) {
- return steps;
- }
- for (int[] dir : DIRS) {
- int rr = at[0] + dir[0];
- int cc = at[1] + dir[1];
- if (!visited[OFFSET + rr][OFFSET + cc]) {
- visited[OFFSET + rr][OFFSET + cc] = true;
- queue.offer(new int[] {rr, cc});
- }
- }
- }
- steps++;
- }
- return 0; // unreachable code
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement