1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| public class ChessBoardCoverage { public static void main(String[] args) { chessBoard(0, 0, 2, 2, BOARD_SIZE); display(); }
private static int BOARD_SIZE = 16 ; private static int[][] board = new int[BOARD_SIZE][BOARD_SIZE]; private static int title = 0;
public static void chessBoard(int tr, int tc, int dr, int dc, int size) { if (size == 1) { return; } int s = size / 2; int num = ++title; if (dr < tr + s && dc < tc + s) { chessBoard(tr, tc, dr, dc, s); } else { board[tr + s - 1][tc + s - 1] = num; chessBoard(tr, tc, tr + s - 1, tc + s - 1, s); } if (dr < tr + s && dc >= tc + s) { chessBoard(tr, tc + s, dr, dc, s); } else { board[tr + s - 1][tc + s] = num; chessBoard(tr, tc + s, tr + s - 1, tc + s, s); } if (dr >= tr + s && dc < tc + s) { chessBoard(tr + s, tc, dr, dc, s); } else { board[tr + s][tc + s - 1] = num; chessBoard(tr + s, tc, tr + s, tc + s - 1, s); } if (dr >= tr + s && dc >= tc + s) { chessBoard(tr + s, tc + s, dr, dc, s); } else { board[tr + s][tc + s] = num; chessBoard(tr + s, tc + s, tr + s, tc + s, s); } }
public static void display() { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board.length; j++) { System.out.printf("%4d", board[i][j]); } System.out.println(""); } } }
|