棋子翻转

棋子翻转

题目描述

在4x4的棋盘上摆满了黑白棋子,黑白两色的位置和数目随机其中左上角坐标为(1,1),右下角坐标为(4,4),现在依次有一些翻转操作,要对一些给定支点坐标为中心的上下左右四个棋子的颜色进行翻转,请计算出翻转后的棋盘颜色。

给定两个数组Af,分别为初始棋盘和翻转位置。其中翻转位置共有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]]
 1 class Flip {
 2 public:
 3     vector<vector<int> > flipChess(vector<vector<int> > A, vector<vector<int> > f) {
 4         // write code here
 5         for(int i=0;i<f.size();i++){
 6             int x=f[i][0]-1;
 7             int y=f[i][1]-1;
 8             
 9             int x1,y1;
10             
11             x1=x;
12             y1=y-1;
13             if(x1>=0&&x1<4&&y1>=0&&y1<4){
14                 int t=A[x1][y1];
15                 t=t==0?1:0;
16                 A[x1][y1]=t;
17             }
18             
19             x1=x;
20             y1=y+1;
21             if(x1>=0&&x1<4&&y1>=0&&y1<4){
22                 int t=A[x1][y1];
23                 t=t==0?1:0;
24                 A[x1][y1]=t;
25             }
26             
27             x1=x-1;
28             y1=y;
29             if(x1>=0&&x1<4&&y1>=0&&y1<4){
30                 int t=A[x1][y1];
31                 t=t==0?1:0;
32                 A[x1][y1]=t;
33             }
34             
35             x1=x+1;
36             y1=y;
37             if(x1>=0&&x1<4&&y1>=0&&y1<4){
38                 int t=A[x1][y1];
39                 t=t==0?1:0;
40                 A[x1][y1]=t;
41             }
42             
43             
44         }
45         return A;
46     }
47 };

注意边界

 1 int main()
 2 {
 3     Flip  fl;
 4     vector<int> A1 = { 0,0,1,1 };
 5     vector<int> A2 = { 1,0,1,0 };
 6     vector<int> A3 = { 0,1,1,0 };
 7     vector<int> A4 = { 0,0,1,0 };
 8     vector<vector<int> > A;
 9     A.push_back(A1);
10     A.push_back(A2);
11     A.push_back(A3);
12     A.push_back(A4);
13 
14     vector<int> f1 = { 2,2 };
15     vector<int> f2 = { 3,3 };
16     vector<int> f3 = { 4,4 };
17     vector<vector<int> > f;
18     f.push_back(f1);
19     f.push_back(f2);
20     f.push_back(f3);
21 
22     vector<vector<int> > re=    fl.flipChess(A, f);
23     
24     return 0;
25 };
原文地址:https://www.cnblogs.com/Renyi-Fan/p/7705058.html