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

        }
    }
}
相关推荐
-凌凌漆-41 分钟前
【freertos】Task创建(v2)
java·开发语言·算法
Nil2081 小时前
leetcode 24两两交换链表中的节点
算法·leetcode·链表
.格子衫.1 小时前
033动态规划之状态压缩DP——算法备赛
算法·动态规划
ysa0510301 小时前
c++常用自带函数用法与注意
c++·笔记·算法
带多刺的玫瑰3 小时前
Leecode#4刷题之寻找两个正序数组的中位数
java·前端·算法
土司大王3 小时前
LeetCode hot100——除了自身以外数组的乘积
数据结构·算法·leetcode
IvanCodes3 小时前
RAG 实战教程(三):向量数据库检索算法,KNN、IVF、HNSW 与 Faiss 实战
人工智能·算法·agent
阿无,3 小时前
布隆过滤器
java·算法·哈希算法
徒慕风流3 小时前
激光雷达回波信号滤波与时刻鉴别算法:原理、代码实现与仿真验证
python·算法·激光雷达