以棋盘为例,用稀疏数组表示二维数组

一、题目

// 要求:将棋盘的黑子和白子用1和2来代替。将下面二维数组以稀疏数组形式表示
//  0 0 0 0 0 0 0 0 0 0 0
//  0 0 1 0 0 0 0 0 0 0 0
//  0 0 0 0 2 0 0 0 0 0 0
//  0 0 0 0 0 0 0 0 0 0 0
//  0 0 0 0 0 0 0 0 0 0 0
//  0 0 0 0 0 0 0 0 0 0 0
//  0 0 0 0 0 0 0 0 0 0 0
//  0 0 0 0 0 0 0 0 0 0 0
//  0 0 0 0 0 0 0 0 0 0 0
//  0 0 0 0 0 0 0 0 0 0 0
//  0 0 0 0 0 0 0 0 0 0 0

//  将以下稀疏数组反向得到原始棋盘数据。其中第一行为棋盘的行列和有效数据个数。后面两行为棋盘数据
//  11 11 2
//  1  2  1
//  2  4  2

二、源代码

package sparseArray;

public class SparseArray {
	/*
	 * 定义打印棋盘的方法
	 */
	public static void printBoard(int[][] chessBoard){  
		for(int[] row : chessBoard) { // forEach遍历
			for(int data : row) {
				System.out.printf("%d\t",data);
			}
			System.out.println();
		}
	}
			
	public static void main(String[] args) { 
		/*
		 * 1. 初始化数据,绘制8*8棋盘.黑棋为1,白棋为2.
		 */
		int[][] chessBoard = new int[8][8];
		chessBoard[2][3] = 1;
		chessBoard[3][4] = 2;
		System.out.println("原始棋盘数据:");
		printBoard(chessBoard); //打印棋盘
		
		/*
		 * 2.统计有效棋子个数
		 */
		int validPieces = 0; //棋盘上有多少个棋子
		for(int[] row : chessBoard) { // forEach遍历
			for(int data : row) {
				if(data != 0) {
					validPieces ++ ;
				}
			}
		}
		
		/*
		 * 3.原始数组转变成稀疏数组
		 */	
		int height = chessBoard.length;
		int width = chessBoard[0].length;
		int[][] simplifiedChessBoard = new int [validPieces+1][3]; //第一行存储棋盘的长宽和有效棋子个数
		simplifiedChessBoard[0][0] = height;
		simplifiedChessBoard[0][1] = width;
		simplifiedChessBoard[0][2] = validPieces;
		
		int count = 0; //计数器用于计数
		for(int i = 0;i < height;i++) {
			for(int j = 0;j < width;j++) {
				if(chessBoard[i][j] != 0) {
					count ++;
					simplifiedChessBoard[count][0] = i;
					simplifiedChessBoard[count][1] = j;
					simplifiedChessBoard[count][2] = chessBoard[i][j];
				}
			}
		}
		
		/*
		 * 4.打印出稀疏数组中的结果
		 */
		System.out.println("\n得到的稀疏数组为:");
		for(int i = 0;i < simplifiedChessBoard.length;i++) {
			System.out.printf("%d\t%d\t%d\t", simplifiedChessBoard[i][0], simplifiedChessBoard[i][1], simplifiedChessBoard[i][2]);
			System.out.println();
		}
		
		/*
		 * 5. 根据稀疏数组打印出原始棋盘数据
		 */
		int[][] restoredChessBoard = new int[simplifiedChessBoard[0][0]][simplifiedChessBoard[0][1]];
		for(int k = 1; k < simplifiedChessBoard.length;k++) {
			restoredChessBoard[simplifiedChessBoard[k][0]][simplifiedChessBoard[k][1]] = simplifiedChessBoard[k][2];
		}
		System.out.println("\n根据稀疏数组打印出原始棋盘数据:");
		printBoard(restoredChessBoard);
	}
}

三、结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值