稀疏数组

public class test11 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
         int[][] arrys = new int[11][11];
         arrys[1][2] = 1 ;
         arrys[2][3] = 1 ;
         System.out.println("输出原始数组:");
         for (int[] is : arrys) {
			for (int is2 : is) {
				System.out.print(is2 + " ");
			}
			System.out.println();
		}
         
         System.out.println("-------------------------------");
         //转换为稀疏数组并保存
         //获取有效值的个数
         int sum = 0;
         for (int[] is : arrys) {
 			for (int is2 : is) {
 				if(is2 != 0) {
 					sum++;
 				}
 			}	
 		}
         System.out.println("有效值的个数为:" + sum);
         
         
         
         //2.创建一个稀疏数组
         int[][] arry2 = new int[sum+1][3];
         int count = 0; 
         arry2[0][0] = 11;
         arry2[0][1] = 11;
         arry2[0][2] = sum;
         
         //遍历数组,寻找非零的数并存入arry2
         for (int i = 0; i < arrys.length; i++) {
			for (int j = 0; j < arrys[i].length; j++) {
				if(arrys[i][j] != 0) {
					count++;
					arry2[count][0] = i;
					arry2[count][1] = j;
					arry2[count][2] = arrys[i][j];
				}
			}
		}
         System.out.println("输出稀疏数组:");
         //输出稀疏数组
         for (int i = 0; i < arry2.length; i++) {
			System.out.println(arry2[i][0] + "\t" + arry2[i][1]+ "\t" + arry2[i][2]);
		}
         
         System.out.println("-------------------------------");
         System.out.println("由稀疏数组再转换成普通数组:");
         
         //1.读取稀疏数组
         int[][] arry3 = new int[arry2[0][0]][arry2[0][1]];
         
         //2.给其中的元素还原他的值
         for (int i = 1; i < arry2.length; i++) {
			arry3[arry2[i][0]][arry2[i][1]] = arry2[i][2];
		}
         System.out.println("-------------------------------");
         System.out.println("输出原始数组:");
         for (int[] is : arry3) {
  			for (int is2 : is) {
  				System.out.print(is2 + " ");
  			}	
  			System.out.println();
  		}
	}

}

控制台:
输出原始数组:
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0

有效值的个数为:2
输出稀疏数组:
行 列 数值
11 11   2
1  2   1
2  3   1

由稀疏数组再转换成普通数组:

输出原始数组:
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值