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 }
复制代码

 

posted @   Dylan_Java_NYC  阅读(1319)  评论(3编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2017-11-26 LeetCode 311. Sparse Matrix Multiplication
点击右上角即可分享
微信分享提示