01java算法与数据结构------稀疏数组代码实现

 1 package com.java.test;
 2 
 3 public class Test {
 4      public static void main(String[] args) {
 5         int[][] chessArr = new int[11][11];
 6         chessArr[1][3]=3;
 7         chessArr[2][1]=5;
 8         chessArr[4][8]=9;
 9         //原始的二维数组输出
10         System.out.println("原始的二维数组输出----------");
11         for (int i = 0; i <chessArr.length ; i++) {
12             for (int j = 0; j <chessArr.length ; j++) {
13                 System.out.print(chessArr[i][j]+" ");
14             }
15             System.out.println();
16         }
17         //获取值的的个数;
18         System.out.println("获取值的的个数---------");
19         int sum=0;
20         for (int i = 0; i <chessArr.length ; i++) {
21             for (int j = 0; j <chessArr.length ; j++) {
22                 if (chessArr[i][j]!=0) {
23                     sum++;
24                 }
25             }
26         }
27         System.out.println("sun:="+sum);
28         //建立稀疏数组
29         int[][] sparesArr = new int[sum+1][3];
30         sparesArr[0][0]=11;
31         sparesArr[0][1]=11;
32         sparesArr[0][2]=sum;
33         int count=1;
34         for (int i = 0; i <chessArr.length ; i++) {
35             for (int j = 0; j <chessArr.length ; j++) {
36                 if (chessArr[i][j]!=0) {
37                     sparesArr[count][0]=i;
38                     sparesArr[count][1]=j;
39                     sparesArr[count][2]=chessArr[i][j];
40                     count++;
41                 }
42             }
43         }
44         //稀疏数组输出
45         System.out.println("稀疏数组输出----------");
46         for (int i = 0; i <sparesArr.length; i++) {
47             for (int j = 0; j <sparesArr.length-1; j++) {
48                 System.out.print(sparesArr[i][j]+" ");
49             }
50             System.out.println();
51         }
52         //稀疏数组转二维数组
53         int[][] chess2Arr = new int[11][11];
54         int coumt1=1;
55         for (int i = 1; i <sparesArr.length; i++) {
56             for (int j = 0; j <1; j++) {
57                 int a=sparesArr[i][j];
58                 int b=sparesArr[coumt1][1];
59                 chess2Arr[a][b]=sparesArr[coumt1][2];
60                 coumt1++;
61              }
62         }
63         //新的二维数组输出
64          System.out.println("新的二维数组输出----------");
65         for (int i = 0; i <chess2Arr.length ; i++) {
66             for (int j = 0; j <chess2Arr.length; j++) {
67                 System.out.print(chess2Arr[i][j]+" ");
68             }
69             System.out.println();
70         }
71     }
72 }

 

posted @ 2021-11-12 19:40  風色  阅读(31)  评论(0)    收藏  举报