棋盘覆盖问题
输入:
棋盘大小、特殊方格的行号和列号
输出:
基本要求:以相同的数字表示一个L型骨牌,输出棋盘中每个方格对应的数字。扩展部分:以图示的方法显示棋盘,以不同的颜色区别L型骨牌。
import java.util.Scanner;
public class Chessboard_coverage_problem {//棋盘覆盖问题 分治
public static void main(String args[]) {
int size = 0,jx = 0,jy = 0;//棋盘规格,棋子位置。
Scanner scanner = new Scanner(System.in);
size = scanner.nextInt();//规格 size * size
jx = scanner.nextInt();//行号
jy = scanner.nextInt();//列号
int [][] arr = chessBoard(size,jx,jy,0);
for(int i = 0;i < size;i++){
for(int j = 0;j < size;j++){
System.out.printf("%d ",arr[i][j]);
}
System.out.printf("\n");
}
}
public static int [][] chessBoard(int size,int jx,int jy,int tag){//规格(size * size) 行号 列号 标记
if(size == 2){
int [][]re = new int[2][2];
for(int i = 0;i < 2;i++){
for(int j = 0;j < 2;j++){
if(!(i == jx && j == jy)){
re[i][j] = tag;
}
}
}
return re;
}
else{
if(jx < size / 2 && jy < size / 2){//奇异点在左上角
return Matrix_replication(chessBoard(size / 2,jx,jy,++tag),chessBoard(size / 2,size / 2 - 1,0,++tag),chessBoard(size / 2,0,size / 2 - 1,++tag),chessBoard(size / 2,0,0,++tag));
}
else if(jx < size / 2 && jy >= size / 2){//奇异点在右上角
return Matrix_replication(chessBoard(size / 2,size / 2 - 1,size / 2 - 1,++tag),chessBoard(size / 2,jx,jy - size / 2,++tag),chessBoard(size / 2,0,size / 2 - 1,++tag),chessBoard(size / 2,0,0,++tag));
}
else if(jx >= size / 2 && jy < size / 2){//奇异点在左下角
return Matrix_replication(chessBoard(size / 2,size / 2 - 1,size / 2 - 1,++tag),chessBoard(size / 2,size / 2 - 1,0,++tag),chessBoard(size / 2,jx - size / 2,jy,++tag),chessBoard(size / 2,0,0,++tag));
}
else {//奇异点在右下角
return Matrix_replication(chessBoard(size / 2,size / 2 - 1,size / 2 - 1,++tag),chessBoard(size / 2,size / 2 - 1,0,++tag),chessBoard(size / 2,0,size / 2 - 1,++tag),chessBoard(size / 2,jx - size / 2,jy - size / 2,++tag));
}
}
}
public static int [][] Matrix_replication(int [][]a11,int [][]a12,int [][]a21,int [][]a22){
if(a11[0].length + a12[0].length != a21[0].length + a22[0].length || a11.length + a21.length != a12.length +a22.length){
return null;
}
int result[][] = new int[a11.length + a21.length][a11[0].length +a12[0].length];//其实a.length == a[0].length 但这边a.length表示行 a[0].length表示列
for(int i = 0;i < a11.length + a21.length;i++){
for(int j = 0;j < a11[0].length +a12[0].length;j++){
if(i < a11.length){//上半部分
if(j < a11[0].length){//左边
result[i][j] = a11[i][j];
}
else{//右边
result[i][j] = a12[i][j - a11[0].length];
}
}
else{//下半部分
if(j < a21[0].length){//左边
result[i][j] = a21[i - a11.length][j];
}
else{//右边
result[i][j] = a22[i - a11.length][j - a12[0].length];
}
}
}
}
return result;
}
}