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);
            }

        }
    }
}
相关推荐
初学者,亦行者4 分钟前
算法设计与分析3:贪心法 - 求解最短路径问题(TSP)
算法·代理模式
Starmoon_dhw9 分钟前
题解:P16108 「o.OI R-1」基础博弈练习题
c++·算法·图论
大鱼>21 分钟前
AI+快递分拣:视觉识别+自动分拣+异常检测
人工智能·深度学习·算法·机器学习
想要成为糕糕手23 分钟前
238. 除了自身以外数组的乘积 — 面试向深度解析
javascript·算法·面试
浩瀚地学35 分钟前
【面试算法笔记】0105-数组-螺旋矩阵
java·开发语言·笔记·算法·面试
Hesionberger1 小时前
动态规划与二分法破解最长递增子序列
java·数据结构·python·算法·leetcode
imuliuliang1 小时前
关于Kruskal 算法在图优化问题中的扩展应用7
算法
老约家的可汗2 小时前
Linux中基础IO
linux·服务器·算法
满怀冰雪2 小时前
第29篇-状态压缩DP-当状态很多时如何降维优化
java·算法·动态规划
令狐掌门2 小时前
2026华为OD面试题020:日志文件异常检测
算法·leetcode·华为od