欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 棋盘覆盖

程序员文章站 2022-05-13 17:19:08
...
import java.util.Scanner;

/**
 * Created by Enzo Cotter on 2018/12/3.
 */
public class ChessBoard {
    static int t = 0;
    static int def[][] = new int[101][101];
    public static void main(String[] args){
        int tr,tc,dr,dc,size;
        System.out.println("请输入棋盘大小(1-100的整数):");
        Scanner input = new Scanner(System.in);
        size = input.nextInt();
        System.out.println("请输入特殊点的左边,横纵坐标最大值都不能超过n:");
        dr = input.nextInt();
        dc = input.nextInt();
        tr = tc = 1;

        chess(tr,tc,dr,dc,size);

        for (int i = 1;i <= size;i++){
            for (int j = 1;j <= size;j++){
                    System.out.print( String.format("%3d" , def[i][j]));
            }
            System.out.println();
        }
    }

    public static void chess(int tr,int tc,int dr,int dc,int size){
        if (size == 1){
            return ;
        }
        t++;
        int tmp = t;//L型骨牌号;
        int s = size/2; //分割棋盘;
        //覆盖左上角棋盘
        if (dr < tr + s && dc <tc + s){
            //特殊方格在此棋盘中
            chess(tr,tc,dr,dc,s);
        }
        else {
            //此棋盘中无特殊方格;
            //用t号L型骨牌覆盖右下角;
            def[tr+s-1][tc+s-1] = tmp;
            //覆盖其余方格;
            chess(tr,tc,tr+s-1,tc+s-1,s);
        }
        //覆盖右上角棋盘
        if (dr < tr + s && dc >= tc + s){
            //特殊方格在此棋盘中
            chess(tr,tc+s,dr,dc,s);
        }
        else {
            //此棋盘中无特殊方格;
            //用t号L型骨牌覆盖左下角
            def[tr+s-1][tc+s] = tmp;
            //覆盖其余方格;
            chess(tr,tc+s,tr+s-1,tc+s,s);
        }
        //覆盖左下角棋盘
        if (dr >= tr+s && dc < tc+s){
            //特殊方格在此棋盘中;
            chess(tr+s,tc,dr,dc,s);
        }
        else {
            //用t号L型骨牌覆盖右上角
            def[tr+s][tc+s-1] = tmp;
            //覆盖其余方格;
            chess(tr+s,tc,tr+s,tc+s-1,s);
        }
        //覆盖右下角棋盘
        if (dr >= tr+s && dc >= tc+s){
            //特殊方格在此棋盘中;
            chess(tr+s,tc+s,dr,dc,s);
        }
        else {
            //用t号L型骨牌覆盖左上角
            def[tr+s][tc+s] = tmp;
            //覆盖其余方格;
            chess(tr+s,tc+s,tr+s,tc+s,s);
        }

    }
}