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

        }
    }
}
相关推荐
smj2302_796826521 天前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
炽烈小老头1 天前
【每天学习一点算法 2026/05/25】矩阵中的最长递增路径
学习·算法·矩阵
叁散1 天前
实验报告:5G 仿真环境与基本链路模拟
算法
从负无穷开始的三次元代码生活1 天前
算法零碎灵感点分享
算法
染指11101 天前
9.LangChain框架(实现RAG)
数据库·人工智能·算法·机器学习·ai·大模型
大数据三康1 天前
在spyder进行的遗传算法练习
开发语言·python·算法
Gene_20221 天前
轮式底盘的微分平坦
算法
吴佳浩1 天前
现代多模态大模型的核心基础:Unified Self-Attention
人工智能·算法·llm
小小编程路1 天前
C++ 常用逻辑运算符
开发语言·c++·算法
Hali_Botebie1 天前
两种子词分词算法BPE (Byte-Pair Encoding) 和Unigram 区别
人工智能·算法