在五子棋游戏中,我们通常会使用一个矩形的二维数组来进行存储当前的游戏状态。这就会造成资源的浪费(绝大多数为空位),这就需要我们进行优化,下面是使用稀疏数组的方式,对五子棋游戏中的存储进行优化。
public class SparseArray {
public static void main(String[] args) {
//创建一个原始的二位数组11*11
//0木有妻子,1,表示黑子 2,表示蓝子
int chessArray[][]= new int[11][11];
chessArray[1][2] = 1;
chessArray[2][4] = 2;
//输出原始的二维数组
System.out.println("原始的二维数组为————————");
for (int[] row:chessArray) {
for (int data:row) {
System.out.printf("%d\t",data);
}
System.out.println();
}
//将二维数组 转 稀疏数组的思想
//1.先遍历二维数组 得到非0数据的个数
int sum = 0;
for (int i = 0;i<11;i++) {
for (int j = 0;j<11;j++) {
if(chessArray[i][j] != 0) {
sum++;
}
}
}
//创建对应的稀疏数组
int sparseArray[][] = new int[sum+1][3];
//给稀疏数组赋值
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
//遍历二维数组,将非0的值存放到sparseArray中
int count = 1 ;
for (int i = 0;i<11;i++) {
for (int j = 0;j<11;j++) {
if(chessArray[i][j] != 0) {
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = chessArray[i][j];
count ++ ;
}
}
}
//输出稀疏数组的形式
System.out.println("得到的稀疏数组为________________");
for (int[] row:sparseArray) {
for (int data : row) {
System.out.printf("%d\t",data);
}
System.out.println();
}
System.out.println("恢复后的数组为______________________");
int chess[][] = new int[sparseArray[0][0]][sparseArray[0][1]];
int num = sparseArray[0][2];
for (int i = 1; i<sparseArray.length; i++) {
chess[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
for (int[] row:chess) {
for (int data:row) {
System.out.printf("%d\t",data);
}
System.out.println();
}
}
}
网友评论