题目描述
在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(); } } }