03-二维数组和稀疏数组-五子棋存盘续盘应用
本讲为数据结构和算法系列第三讲,聚焦二维数组与稀疏数组的工程应用。
核心内容
- 二维数组存储与遍历
- 稀疏数组概念:压缩二维数组中大量 0 元素
- 二维数组 ↔ 稀疏数组转换
- 五子棋存盘续盘应用实战
java
// 二维数组转稀疏数组
public class SparseArray {
public static int[][] toSparse(int[][] chess) {
int count = countNonZero(chess);
int[][] sparse = new int[count + 1][3];
sparse[0] = new int[]{chess.length, chess[0].length, count};
int idx = 1;
for (int i = 0; i < chess.length; i++)
for (int j = 0; j < chess[i].length; j++)
if (chess[i][j] != 0)
sparse[idx++] = new int[]{i, j, chess[i][j]};
return sparse;
}
public static int[][] toChess(int[][] sparse) {
int[][] chess = new int[sparse[0][0]][sparse[0][1]];
for (int i = 1; i < sparse.length; i++)
chess[sparse[i][0]][sparse[i][1]] = sparse[i][2];
return chess;
}
}五子棋存盘续盘
- 存盘:将棋盘二维数组压缩为稀疏数组后写入文件
- 续盘:读取稀疏数组后还原二维棋盘
- 优势:当棋盘大部分为 0 时可显著降低存储开销