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

        }
    }
}
相关推荐
秋天的怀念_David5 分钟前
算法一千零一夜 · 第四十夜 · 错层的状态码
java·程序人生·算法
纪念 22910 分钟前
C++ 算法模板与错题 (差分)
开发语言·c++·算法
echoliuy33 分钟前
二叉树—二叉搜索树 前序 中序 后序
算法·深度优先
怕浪猫37 分钟前
机器人是当下薪酬最高却几乎没人学的技能:一份 6 个月从 0 到上手的学习路线
算法·架构·github
MobotStone1 小时前
打造高性价比 AI 应用:选对模型、用好缓存、持续测试
人工智能·算法
金榜题名萱1 小时前
蓝桥杯|石子合并(区间动态规划)
c语言·数据结构·c++·算法·蓝桥杯·动态规划
纪念 2291 小时前
C++ 算法模板与错题 (前缀和)
开发语言·c++·算法
罗西的思考2 小时前
【轻量化复刻大模型 / π0.5】(4)处理输入
人工智能·算法·机器学习
饮水桶_T2 小时前
DUNE:基于依赖图传播的Agent派生记忆一致性更新机制 笔记
开发语言·笔记·算法·电脑
Navigator_Z2 小时前
LeetCode //C - 1332. Remove Palindromic Subsequences
c语言·算法·leetcode