美文网首页
稀疏数组实现与转换

稀疏数组实现与转换

作者: YAOPRINCESS | 来源:发表于2020-06-30 17:44 被阅读0次
import java.io.*;
import java.util.*;
public class SparseArray{

    //由于使用cmd运行java程序的时候,系统默认的编码格式是gbk。而包含中文字符的代码一般是utf-8格式,所以直接运行含有中文字符的代码就会出现编码错误。
    //指定编码  -encoding utf-8
    public static void main(String[] args) {
        // 创建原始二位数组11*11
        // 0表示没有棋子,1表示白子,2表示黑子
        int[][] chessArray = new int[11][11];// new创建空间
        chessArray[1][2] = 1;
        chessArray[2][3] = 2;
        for ( int[] row : chessArray) {
            for ( int data : row) {
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        System.out.println();

        //构建稀疏数组
        int count=0;//记录非零元素个数
        //1.计算第0行数据:行数,列数,非0元素个数
        //求非零元素个数
        for( int[] row : chessArray){
            for( int data :row){
                if(data!=0)
                    count++;
            }
        }

        int[][] sparseArray = new int [count+1][3];
        sparseArray[0][0]=chessArray.length;
        sparseArray[0][1]=chessArray[0].length;
        sparseArray[0][2]=count;

        int index=1;
        //往sparseArray中添加非零结点
        for( int i=0;i<chessArray.length;i++){
            for(int j=0;j<chessArray[0].length;j++){
                if(chessArray[i][j]!=0){
                    sparseArray[index][0]=i;
                    sparseArray[index][1]=j;
                    sparseArray[index++][2]=chessArray[i][j];
                }
            }
        }
        for( int[] row:sparseArray){
            for(int data:row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }

        System.out.println();
        //根据稀疏数组转换回原数组

        int[][] originalArray=new int[sparseArray[0][0]][sparseArray[0][1]];
        for(int i=1;i<=sparseArray[0][2];i++){//i<sparseArray.length
            originalArray[sparseArray[i][0]][sparseArray[i][1]]=sparseArray[i][2];
        }
        //打印结果
        for(int[] row:originalArray){
            for(int data:row){
                System.out.printf("%d\t",data);
            }
            System.out.println();
        }
    }    
}
image.png

相关文章

网友评论

      本文标题:稀疏数组实现与转换

      本文链接:https://www.haomeiwen.com/subject/rfoxqktx.html