//package java.array;
public class arrayDome8 {
public static void main(String[] args) {
//创建一个二维数组 0 代表没有棋子1代表黑棋2代表白棋子
int[][] array1=new int[11][11];//一个11*11的棋盘里面没有赋值
array1[1][2]=1;
array1[2][3]=2;
System.out.println("输出原始数组");//输出原始数组
for (int[] ints : array1) {//打印二维数组
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();//换行
}
//转换为稀疏数组
//获取有效值的个数
int sub=0;
for (int i=0; i < 11; i++) {
for (int j=0; j < 11; j++) {
if (array1[i][j] != 0) {
sub++;//看有多少个有效数组
}
}
}
System.out.println("有效值的个数" + sub);
//创建一个稀疏数组对应得数组array2
int[][] array2=new int[sub + 1][3];//
array2[0][0]=11;//存了多少行
array2[0][1]=11;//存了多少列
array2[0][2]=sub;//有几个有效的值
//遍历二维数组,将非零的值,存放到稀疏数组中
int count=0;//计数的作用
for (int i=0; i < array1.length; i++) {
for (int j=0; j < array1[i].length; j++) {
if (array1[i][j]!=0){
count++;
array2[count][0] = i;//数组2第几行第几列的值
array2[count][1] = j;
array2[count][2] = array1[i][j];//数组1具体的数
}
}
}
//稀疏数组为
System.out.println("稀疏数组为");
for (int i=0; i < array2.length; i++) {
System.out.println(array2[i][0] + "\t" + array2[i][1] + "\t" + array2[i][2] + "\t");
}
System.out.println("=================================================================");
//稀疏数组转化为原始数组
int mma = 0;
int[][] array3 = new int[array2[0][0]][array2[0][1]];//数组的长宽array2[0][0]][array2[0][1] 11 11
//给其中的元素还原它的值
for (int i=1; i <array2.length ; i++) {
array3[array2[i][0]][array2[i][1]] = array2[i][2];
}
System.out.println("打印还原数组:");
for (int[] ints : array3) {//打印二维数组
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();//换行
}
}
}
//package java.array;
public class arrayDome9 {
public static void main(String[] args) {
int[][] array1 = new int[5][5];
array1[0][1] = 6;
array1[0][3] = 6;
array1[1][0] = 6;
array1[1][1] = 6;
array1[1][2] = 6;
array1[1][3] = 6;
array1[1][4] = 6;
array1[2][1] = 6;
array1[2][2] = 6;
array1[2][3] = 6;
array1[3][2] = 6;
array1[4][1] = 5;
array1[4][2] = 2;
System.out.println("fall in love");
//编译状态下最好把6连接起来
for (int[] ints : array1) {
for (int anInt : ints) {
System.out.print(anInt + "\t");
}
System.out.println();
}
//转换为稀疏数组
//看有多少个有效数组
//创建一个稀疏数组对应得数组array2
//存了多少行
//存了多少列
//有几个有效的值
//遍历二维数组,将非零的值,存放到稀疏数组中
int sub = 0;
for (int i=0; i <5 ; i++) {
for (int j=0; j <5 ; j++) {
if (array1[i][j]!=0){
sub++;
}
}
}
System.out.println("有效值的个数为:" + sub);
int[][] array2 = new int[sub+1][3];
array2[0][0] = 5;
array2[0][1] = 5;
array2[0][2] =sub;
int aaa = 0;
for (int i=0; i <array1.length ; i++) {
for (int j=0; j < array1[i].length; j++) {
if (array1[i][j]!=0){
aaa++;
array2[aaa][0]=i;
array2[aaa][1]=j;
array2[aaa][2]=array1[i][j];
}
}
}
System.out.println("稀疏数组为");
for (int i=0; i <array2.length ; i++) {
System.out.println(array2[i][0] + "\t" +array2[i][1] + "\t" + array2[i][2] + "\t");
}
}
}