P1443 马的遍历(洛谷)

题目:P1443 马的遍历(洛谷)_第1张图片



import java.util.Scanner;

public class Main{
    static int[][] a;
    static boolean vis[][];
    static int n;
    static int m;
    static int[] xx=new int[]{1,2,-2,-1,1,-2,-1,2};
    static int[] yy=new int[]{2,1,-1,-2,-2,1,2,-1};
    public static void dfs(int x,int y,int count){
        if(count>200)//阈值
            return;
        a[x][y]=count;
        for (int i = 0; i < xx.length; i++) {
            if(x+xx[i]>=0&&x+xx[i]<n&&y+yy[i]>=0&&y+yy[i]<m
            &&(a[x+xx[i]][y+yy[i]]==-1||a[x+xx[i]][y+yy[i]]>count+1)){
                dfs(x+xx[i],y+yy[i],count+1);
            }
        }
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        m=sc.nextInt();
        a=new int[n][m];
        vis=new boolean[n][m];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                a[i][j]=-1;
                vis[i][j]=false;
            }
        }
        int sx=sc.nextInt();
        int sy=sc.nextInt();
        dfs(sx-1,sy-1,0);
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                System.out.printf("%-5d",a[i][j]);
            }
            System.out.println();
        }
    }
}

你可能感兴趣的:(蓝桥杯)