public class Main {
private int[][] commonArray;
public static void main(String[] args) {
Main main = new Main();
main.initCommonArray();
int[][] sparseArray = main.toSparseArray(main.commonArray);
main.toCommonArray( sparseArray );
}
public void initCommonArray(){
commonArray = new int[9][9];
commonArray[1][1] = 2;
commonArray[2][2] = 3;
System.out.println("普通数组为: ");
for ( int i=0; i<9; i++ ){
for ( int j=0; j<9; j++ ){
System.out.print(commonArray[i][j] + " ");
}
System.out.println();
}
System.out.println();
}
/**
* 二维数组转稀疏数组
* */
public int[][] toSparseArray( int[][] commonArray ) {
if ( commonArray != null && commonArray.length > 0 ){
//获取数组的长宽
int totalLength = commonArray.length;
int totalWidth = commonArray[0].length;
//扫描数组的有效数据的长度
int availableCount = 0;
for ( int i=0; i<commonArray.length; i++ ){
int[] temp = commonArray[i];
for ( int j=0; j<temp.length; j++ ){
if ( commonArray[i][j] != 0 ){
availableCount++;
}
}
}
int[][] spareArray = new int[availableCount+1][3];
spareArray[0][0] = totalLength; //存二维数组的长度
spareArray[0][1] = totalWidth; //存二维数组的宽度
spareArray[0][2] = 0; //存二维数组中初始化的值
int k = 1;
for ( int i=0; i<commonArray.length; i++ ){
int[] temp = commonArray[i];
for ( int j=0; j<temp.length; j++ ){
if ( commonArray[i][j] != 0 ){
spareArray[k][0] = i;
spareArray[k][1] = j;
spareArray[k][2] = commonArray[i][j];
k++;
}
}
}
System.out.println("转换成的稀疏数组为: ");
for ( int i=0; i<spareArray.length; i++ ){
int[] temp = spareArray[i];
for ( int j=0; j<temp.length; j++ ){
System.out.print(spareArray[i][j] + " ");
}
System.out.println();
}
System.out.println();
return spareArray;
}
return null;
}
/**
* 稀疏数组转二维数组
* */
public void toCommonArray( int[][] sparseArray ){
if ( sparseArray == null || sparseArray.length == 0 ){
return;
}
//根据第一行获取二维数组的高宽,以及默认值
int height = sparseArray[0][0];
int width = sparseArray[0][1];
int defaultValue = sparseArray[0][2];
int[][] commonArray = new int[height][width];
for ( int i=0; i<height; i++ ){
for ( int j=0; j<width; j++ ){
commonArray[i][j] = defaultValue;
}
}
//将有效数据填充到数组中
for ( int i=1; i<sparseArray.length; i++ ){
int y = sparseArray[i][0];
int x = sparseArray[i][1];
int value = sparseArray[i][2];
commonArray[y][x] = value;
}
System.out.println("稀疏矩阵转普通数组为: ");
for ( int i=0; i<height; i++ ){
for ( int j=0; j<width; j++ ){
System.out.print(commonArray[i][j] + " ");
}
System.out.println();
}
}
}
JAVA 二维数组与稀疏数组转换
最新推荐文章于 2024-03-07 18:24:29 发布
本文介绍了一种将二维数组转换为稀疏数组的方法,以及如何从稀疏数组还原回二维数组。通过扫描二维数组的有效数据,创建了一个包含数组尺寸和非零元素位置及值的稀疏数组。
728

被折叠的 条评论
为什么被折叠?



