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

        }
    }
}
相关推荐
田梓燊1 分钟前
leetcode 240
算法·leetcode·职场和发展
wenhaoran116 分钟前
CF1800F Dasha and Nightmares
c++·算法·字符串·codeforces·位运算
We་ct10 分钟前
LeetCode 149. 直线上最多的点数:题解深度剖析
前端·javascript·算法·leetcode·typescript
sheeta199810 分钟前
LeetCode 每日一题笔记 日期:2026.04.13 题目:1848.到目标元素的最小距离
笔记·算法·leetcode
Anycall.Q14 分钟前
RULE (ICLR 2026)
算法
断眉的派大星19 分钟前
数据结构——指针
数据结构·算法
Xpower 1721 分钟前
算法学习笔记 Day 1:迁移学习与域自适应(DANN/CORAL)
笔记·学习·算法
橘颂TA29 分钟前
【笔试】算法的暴力美学——牛客 NC242:单词搜索,思路:dfs 算法
算法·深度优先
沐苏瑶1 小时前
Java据结构深度解析:AVL 树与红黑树
数据结构·算法
feifeigo1231 小时前
MATLAB中对转子建立有限元模型并进行动力学计算
算法