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

        }
    }
}
相关推荐
CS创新实验室33 分钟前
从盘边到芯端——硬盘接口七十年变迁史
算法·磁盘调度
xvhao20131 小时前
单源、多源最短路
数据结构·c++·算法·深度优先·动态规划·图论·图搜索算法
MATLAB代码顾问1 小时前
多种群协同进化算法(MPCE)求解大规模作业车间调度问题——附MATLAB代码
开发语言·算法·matlab
FQNmxDG4S1 小时前
JVM内存模型详解:堆、栈、方法区与垃圾回收
java·jvm·算法
We་ct2 小时前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划
AI科技星2 小时前
精细结构常数α作为SI 7大基本量纲统一耦合常数的量子几何涌现理论
算法·机器学习·数学建模·数据挖掘·量子计算
txzrxz2 小时前
动态规划——背包问题
算法·动态规划
Yingye Zhu(HPXXZYY)2 小时前
洛谷 P15553 [CCPC 2025 哈尔滨站] 液压机
算法
谭欣辰3 小时前
LCS(最长公共子序列)详解
开发语言·c++·算法
m0_629494733 小时前
LeetCode 热题 100-----17.缺失的第一个正数
数据结构·算法·leetcode