解答:名企笔试:美团2016校招(棋子翻转)

题目描述


在4×4的棋盘上摆满了黑白棋子,黑白两色的位置和数目随机其中左上角坐标为(1,1),右下角坐标为(4,4),现在依次有一些翻转操作,要对


一些给定支点坐标为中心的上下左右四个棋子的颜色进行翻转,请计算出翻转后的棋盘颜色。


给定两个数组A和f,分别为初始棋盘和翻转位置。其中翻转位置共有3个。请返回翻转后的棋盘。


测试样例:


[[0,0,1,1],[1,0,1,0],[0,1,1,0],[0,0,1,0]],[[2,2],[3,3],[4,4]]


返回:


[[0,1,1,1],[0,0,1,0],[0,1,1,0],[0,0,1,0]]



代码如下:

public class Reversi {

	public static void main(String[] args) {
		int[][] chess = { { 0, 0, 1, 1 }, { 1, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 } };
		int[][] positions = { { 2, 2 }, { 3, 3 }, { 4, 4 } };
		reversal(chess, positions);
	}

	public static void reversal(int[][] chess, int[][] positions) {
		for (int i = 0; i < chess.length; i++) {
			for(int j=0;j<chess[i].length;j++){
				System.out.print(chess[i][j]+"  ");
			}
			System.out.println();
		}
		System.out.println();
		System.out.println();
		for (int p = 0; p < positions.length; p++) {
			int x = positions[p][0] - 1;// -1转化为数组位置
			int y = positions[p][1] - 1;
			// 是否存在左边的位置
			if (x > 0) {
				chess[x - 1][y] = chess[x - 1][y] ^ 1;
			}
			// 是否存在右边的位置
			if (x < chess.length - 1) {
				chess[x + 1][y] = chess[x + 1][y] ^ 1;
			}
			// 是否存在上边的位置
			if (y > 0) {
				chess[x][y - 1] = chess[x][y - 1] ^ 1;
			}
			// 是否存在下边的位置
			if (y < chess[0].length - 1) {
				chess[x][y + 1] = chess[x][y + 1] ^ 1;
			}
			for (int i = 0; i < chess.length; i++) {
				for(int j=0;j<chess[i].length;j++){
					System.out.print(chess[i][j]+"  ");
				}
				System.out.println();
			}
			System.out.println();
			System.out.println();
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值