November 20, 2022

1197. Minimum Knight Moves

1197. Minimum Knight Moves

BFS. Note: Using the HashSet to keep track of the visited cells in the Java implementation will result in the TLE (Time Limit Exceeded) exception.

class Solution {
    public int minKnightMoves(int x, int y) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0});
        int[][] dirs = `{`{1, 2}, {2, 1}, {-2, 1}, {-1, 2}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}`}`;
        boolean[][] visited = new boolean[602][602];
        
        int moves = 0;
        while(!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] cur = queue.poll();
                if (cur[0] == x && cur[1] == y) {
                    return moves;
                }
                for (int[] dir : dirs) {
                    int row = cur[0] + dir[0];
                    int col = cur[1] + dir[1];
                    if (row < -300 || row > 300 || col < -300 || col > 300 || visited[row + 301][col + 301]) {
                        continue;
                    }
                    queue.offer(new int[]{row, col});
                    visited[row + 301][col + 301] = true;
                }
            }
            moves ++;
        }
        return -1;
        
    }
}
comments powered by Disqus