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

        }
    }
}
相关推荐
前端小刘哥22 分钟前
赋能在线教育与企业培训:视频直播点播平台EasyDSS视频点播的核心技术与应用实践
算法
吗~喽29 分钟前
【LeetCode】四数之和
算法·leetcode·职场和发展
Net_Walke39 分钟前
【散列函数】哈希函数简介
算法·哈希算法
卿言卿语1 小时前
CC1-二叉树的最小深度
java·数据结构·算法·leetcode·职场和发展
码流之上1 小时前
【一看就会一写就废 指间算法】执行操作后的最大 MEX —— 同余、哈希表
算法·面试
仰泳的熊猫1 小时前
LeetCode:889. 根据前序和后序遍历构造二叉树
数据结构·c++·算法
2025年一定要上岸1 小时前
【日常学习】10-15 学习re
学习·算法·正则表达式
aramae2 小时前
数据结构与算法(递归)
开发语言·经验分享·笔记·算法
小欣加油2 小时前
leetcode 329 矩阵中的最长递增路径
c++·算法·leetcode·矩阵·深度优先·剪枝
Emilia486.2 小时前
【Leetcode&nowcode&数据结构】单链表的应用(初阶)
c语言·数据结构·算法·leetcode