“二维数组”转“稀疏数组”实现思路:
1)遍历二维数组,得到有效数据个数sum
2)根据sum就可以创建稀疏数组sparseArray[sum+1,3]
3)将二维数组有效数据存到稀疏数组中
“稀疏数组”转“二维数组”实现思路:
1)读取稀疏数组第一行创建原始二维数组
2)从稀疏数组第二行开始读取数据到二维数组
C#实现代码:
1 using System; 2 3 namespace 数据结构 4 { 5 public class SparseArray 6 { 7 static void Main(string[] args) 8 { 9 #region 创建原始二维数组 10 //0表示没有棋子,1表示白棋,2表示黑棋 11 int row = 11; 12 int col = 11; 13 int[,] chessAarry1 = new int[row, col]; 14 chessAarry1[1, 2] = 1; 15 chessAarry1[2, 3] = 2; 16 chessAarry1[5, 6] = 1; 17 chessAarry1[3, 5] = 2; 18 19 //打印二维数组 20 Console.WriteLine("打印原始二维数组:"); 21 for (int r = 0; r < chessAarry1.GetLength(0); r++) 22 { 23 for (int i = 0; i < chessAarry1.GetLength(1); i++) 24 { 25 Console.Write($"{chessAarry1[r, i]} "); 26 } 27 Console.WriteLine(""); 28 } 29 #endregion 30 31 #region 创建稀疏数组 32 //(1)统计原始二维数组有效数据 33 int sum = 0; 34 foreach (var item in chessAarry1) 35 { 36 if (item > 0) sum++; 37 } 38 int[,] sparseArray = new int[sum + 1, 3]; 39 sparseArray[0, 0] = row; 40 sparseArray[0, 1] = col; 41 sparseArray[0, 2] = sum; 42 43 //(2)从原始二维数组读取有效数据到稀疏数组 44 int insert = 0; 45 for (int r = 0; r < chessAarry1.GetLength(0); r++) 46 { 47 for (int i = 0; i < chessAarry1.GetLength(1); i++) 48 { 49 var val = chessAarry1[r, i]; 50 if (val > 0) 51 { 52 insert++; 53 sparseArray[insert, 0] = r; 54 sparseArray[insert, 1] = i; 55 sparseArray[insert, 2] = val; 56 } 57 if (sum == insert) break; 58 } 59 if (sum == insert) break; 60 } 61 62 //打印稀疏数组 63 Console.WriteLine("打印稀疏数组:"); 64 for (int r = 0; r < sparseArray.GetLength(0); r++) 65 { 66 Console.WriteLine($"{sparseArray[r, 0]} {sparseArray[r, 1]} {sparseArray[r, 2]}"); 67 } 68 #endregion 69 70 #region 恢复原始二维数组 71 //(1)创建所有元素都为0的二维数组 72 int row2 = sparseArray[0, 0]; 73 int col2 = sparseArray[0, 1]; 74 int val2 = sparseArray[0, 2]; 75 int[,] chessAarry2 = new int[row2, col2]; 76 //(2)从稀疏数组读取有效数据到原始二维数组 77 for (int r = 1; r < sparseArray.GetLength(0); r++) 78 { 79 row2 = sparseArray[r, 0]; 80 col2 = sparseArray[r, 1]; 81 val2 = sparseArray[r, 2]; 82 chessAarry2[row2, col2] = val2; 83 } 84 85 //打印二维数组 86 Console.WriteLine("打印原始二维数组:"); 87 for (int r = 0; r < chessAarry2.GetLength(0); r++) 88 { 89 for (int i = 0; i < chessAarry2.GetLength(1); i++) 90 { 91 Console.Write($"{chessAarry2[r, i]} "); 92 } 93 Console.WriteLine(); 94 } 95 #endregion 96 } 97 } 98 }