Welcome to Subscribe On Youtube

1197. Minimum Knight Moves

Description

In an infinite chess board with coordinates from -infinity to +infinity, you have a knight at square [0, 0].

A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

Return the minimum number of steps needed to move the knight to the square [x, y]. It is guaranteed the answer exists.

 

Example 1:

Input: x = 2, y = 1
Output: 1
Explanation: [0, 0] → [2, 1]

Example 2:

Input: x = 5, y = 5
Output: 4
Explanation: [0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]

 

Constraints:

  • -300 <= x, y <= 300
  • 0 <= |x| + |y| <= 300

Solutions

Solution 1: BFS

This problem can be solved using the BFS shortest path model. The search space for this problem is not large, so we can directly use the naive BFS. The solution below also provides the code for bidirectional BFS for reference.

Bidirectional BFS is a common optimization method for BFS. The main implementation ideas are as follows:

  1. Create two queues, q1 and q2, for “start -> end” and “end -> start” search directions, respectively.
  2. Create two hash maps, m1 and m2, to record the visited nodes and their corresponding expansion times (steps).
  3. During each search, prioritize the queue with fewer elements for search expansion. If a node visited from the other direction is found during the expansion, it means the shortest path has been found.
  4. If one of the queues is empty, it means that the search in the current direction cannot continue, indicating that the start and end points are not connected, and there is no need to continue the search.
  • class Solution {
        public int minKnightMoves(int x, int y) {
            x += 310;
            y += 310;
            int ans = 0;
            Queue<int[]> q = new ArrayDeque<>();
            q.offer(new int[] {310, 310});
            boolean[][] vis = new boolean[700][700];
            vis[310][310] = true;
            int[][] dirs = { {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1} };
            while (!q.isEmpty()) {
                for (int k = q.size(); k > 0; --k) {
                    int[] p = q.poll();
                    if (p[0] == x && p[1] == y) {
                        return ans;
                    }
                    for (int[] dir : dirs) {
                        int c = p[0] + dir[0];
                        int d = p[1] + dir[1];
                        if (!vis[c][d]) {
                            vis[c][d] = true;
                            q.offer(new int[] {c, d});
                        }
                    }
                }
                ++ans;
            }
            return -1;
        }
    }
    
  • class Solution {
    public:
        int minKnightMoves(int x, int y) {
            x += 310;
            y += 310;
            int ans = 0;
            queue<pair<int, int>> q;
            q.push({310, 310});
            vector<vector<bool>> vis(700, vector<bool>(700));
            vis[310][310] = true;
            vector<vector<int>> dirs = { {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1} };
            while (!q.empty()) {
                for (int k = q.size(); k > 0; --k) {
                    auto p = q.front();
                    q.pop();
                    if (p.first == x && p.second == y) return ans;
                    for (auto& dir : dirs) {
                        int c = p.first + dir[0], d = p.second + dir[1];
                        if (!vis[c][d]) {
                            vis[c][d] = true;
                            q.push({c, d});
                        }
                    }
                }
                ++ans;
            }
            return -1;
        }
    };
    
  • class Solution:
        def minKnightMoves(self, x: int, y: int) -> int:
            q = deque([(0, 0)])
            ans = 0
            vis = {(0, 0)}
            dirs = ((-2, 1), (-1, 2), (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1))
            while q:
                for _ in range(len(q)):
                    i, j = q.popleft()
                    if (i, j) == (x, y):
                        return ans
                    for a, b in dirs:
                        c, d = i + a, j + b
                        if (c, d) not in vis:
                            vis.add((c, d))
                            q.append((c, d))
                ans += 1
            return -1
    
    
  • func minKnightMoves(x int, y int) int {
    	x, y = x+310, y+310
    	ans := 0
    	q := [][]int{ {310, 310} }
    	vis := make([][]bool, 700)
    	for i := range vis {
    		vis[i] = make([]bool, 700)
    	}
    	dirs := [][]int{ {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1} }
    	for len(q) > 0 {
    		for k := len(q); k > 0; k-- {
    			p := q[0]
    			q = q[1:]
    			if p[0] == x && p[1] == y {
    				return ans
    			}
    			for _, dir := range dirs {
    				c, d := p[0]+dir[0], p[1]+dir[1]
    				if !vis[c][d] {
    					vis[c][d] = true
    					q = append(q, []int{c, d})
    				}
    			}
    		}
    		ans++
    	}
    	return -1
    }
    
  • use std::collections::VecDeque;
    
    const DIR: [(i32, i32); 8] = [
        (-2, 1),
        (2, 1),
        (-1, 2),
        (1, 2),
        (2, -1),
        (-2, -1),
        (1, -2),
        (-1, -2),
    ];
    
    impl Solution {
        #[allow(dead_code)]
        pub fn min_knight_moves(x: i32, y: i32) -> i32 {
            // The original x, y are from [-300, 300]
            // Let's shift them to [0, 600]
            let x: i32 = x + 300;
            let y: i32 = y + 300;
            let mut ret = -1;
            let mut vis: Vec<Vec<bool>> = vec![vec![false; 618]; 618];
            // <X, Y, Current Steps>
            let mut q: VecDeque<(i32, i32, i32)> = VecDeque::new();
    
            q.push_back((300, 300, 0));
    
            while !q.is_empty() {
                let (i, j, s) = q.front().unwrap().clone();
                q.pop_front();
                if i == x && j == y {
                    ret = s;
                    break;
                }
                Self::enqueue(&mut vis, &mut q, i, j, s);
            }
    
            ret
        }
    
        #[allow(dead_code)]
        fn enqueue(
            vis: &mut Vec<Vec<bool>>,
            q: &mut VecDeque<(i32, i32, i32)>,
            i: i32,
            j: i32,
            cur_step: i32
        ) {
            let next_step = cur_step + 1;
            for (dx, dy) in DIR {
                let x = i + dx;
                let y = j + dy;
                if Self::check_bounds(x, y) || vis[x as usize][y as usize] {
                    // This <X, Y> pair is either out of bound, or has been visited before
                    // Just ignore this pair
                    continue;
                }
                // Otherwise, add the pair to the queue
                // Also remember to update the vis vector
                vis[x as usize][y as usize] = true;
                q.push_back((x, y, next_step));
            }
        }
    
        #[allow(dead_code)]
        fn check_bounds(i: i32, j: i32) -> bool {
            i < 0 || i > 600 || j < 0 || j > 600
        }
    }
    
    

All Problems

All Solutions