P1443 马的遍历

题目描述:

有一个 𝑛×𝑚n×m 的棋盘,在某个点 (𝑥,𝑦)(x,y) 上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步。

代码:

java 复制代码
package lanqiao;

import java.util.*;

public class Main {
    static int n,m,x,y;
    static int[][] a = new int[410][410];
    static int[] aa = new int[] {2, 1, 2, -1, -2, -1, -2, 1};
    static int[] bb = new int[] {1, 2, -1, -2, -1, 2, 1, -2};
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        x = sc.nextInt();
        y = sc.nextInt();
        //初始化数组
        for(int i = 1;i <= n;i ++)
        {
            for(int j = 1;j <= m;j ++)
            {
                a[i][j] = -1;
            }
        }
        dfs(x,y,0);
        a[x][y] = 0;
        for(int i = 1;i <= n;i ++)
        {
            for(int j = 1;j <= m;j ++)
            {
                System.out.printf("%-5d", a[i][j]);
            }
            System.out.println();
        }
    }

    public static void dfs(int x,int y,int t)
    {
        if(t >200) //DFS不加剪枝的话需要加阙值
        {
            return;
        }

        a[x][y] = t;
        for(int i = 0;i < 8;i ++)
        {
            if(x + aa[i] >= 1 && y + bb[i] >= 1 && x + aa[i] <= n && y + bb[i] <= m
                    && (a[x + aa[i]][y + bb[i]] == -1 || a[x + aa[i]][y + bb[i]] > t + 1))//需要对未走过的格子,或者新路线步数较短的格子进行重新赋值
            {
                dfs(x + aa[i],y + bb[i],t + 1);
            }

        }
    }
}
相关推荐
Mem0rin3 分钟前
[Java]排序
java·算法·排序算法
qeen8724 分钟前
【算法笔记】差分与经典例题解析
c语言·c++·笔记·学习·算法·差分
kronos.荒29 分钟前
动态规划——整数拆分(python)
python·算法·动态规划
cici1587436 分钟前
基于Koopman模型预测控制的非线性流控制数据驱动框架
算法
6Hzlia37 分钟前
【Hot 100 刷题计划】 LeetCode 416. 分割等和子集 | C++ 0-1背包 1D空间极致优化
c++·算法·leetcode
穿条秋裤到处跑39 分钟前
每日一道leetcode(2026.04.21):执行交换操作后的最小汉明距离
java·算法·leetcode
Tina学编程40 分钟前
算法训练Day10 | LeetCode 169 多数元素
算法·leetcode
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2026.04.22 题目:2452. 距离字典两次编辑以内的单词
笔记·算法·leetcode
ZPC82101 小时前
nmtui
人工智能·算法·机器人
_深海凉_1 小时前
LeetCode热题100-全排列
算法·leetcode·职场和发展