LeetCode 1197. Minimum Knight Moves


原題鏈接在這里:https://leetcode.com/problems/minimum-knight-moves/

題目:

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:

  • |x| + |y| <= 300

題解:

It is asking the minimum steps to get to (x, y). Thus, use BFS to iterate from (0, 0).

But how to make it faster. Since it is symmatic, we could focus on 1/4 directions.

Make x = |x|, y = |y|. Thus when doing BFS, besides checking it is visited, we also need to check it is within the boundary.

The bounday is >= -1. The reason it the shortest path may need the node on x =-1, y =-1. e.g. shortest path to (1, 1) is (0,0) -> (-1, 2) -> (1, 1).

Time Complexity: O(V+E). V is node count. E is edge count.

Space: O(V).

AC Java:

 1 class Solution {
 2     int [][] dirs = new int[][]{{-1, -2}, {-1, 2}, {1, -2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}};
 3     
 4     public int minKnightMoves(int x, int y) {
 5         x = Math.abs(x);
 6         y = Math.abs(y);
 7         
 8         HashSet<String> visited = new HashSet<>();
 9         LinkedList<int []> que = new LinkedList<>();
10         que.add(new int[]{0, 0});
11         visited.add("0,0");
12         
13         int step = 0;
14         while(!que.isEmpty()){
15             int size = que.size();
16             while(size-->0){
17                 int [] cur = que.poll();
18                 if(cur[0] == x && cur[1] == y){
19                     return step;
20                 }
21 
22                 for(int [] dir : dirs){
23                     int i = cur[0] + dir[0];
24                     int j = cur[1] + dir[1];
25                     if(!visited.contains(i+","+j) && i>=-1 && j>=-1){
26                         que.add(new int[]{i, j});
27                         visited.add(i+","+j);
28                     }
29                 }
30             }
31             
32             step++;
33         }
34         
35         return -1;
36     }
37 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM