题目描述
在4x4的棋盘上摆满了黑白棋子,黑白两色的位置和数目随机其中左上角坐标为(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]]
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class Flip {
public int[][] flipChess(int[][] A, int[][] f) {
// write code here
if(A==null||A.length==0||f.length==0||f==null)return A;
HashMap<String, Integer> map = new HashMap<String, Integer>();
int row = 0;
int col =0;
//(row,col)是下标
for (int i = 0; i < f.length; i++) {
//上下左右四个下标
int a = f[i][0]-1;
int b = f[i][1]-1;
String up = (a-1)+","+b;
if(map.containsKey(up)) {
map.put(up, map.get(up)+1);
}else {
map.put(up, 1);
}
String down = (a+1)+","+b;
if(map.containsKey(down)) {
map.put(down, map.get(down)+1);
}else {
map.put(down, 1);
}
String left = a+","+(b-1);
if(map.containsKey(left)) {
map.put(left, map.get(left)+1);
}else {
map.put(left, 1);
}
String right = a+","+(b+1);
if(map.containsKey(right)) {
map.put(right, map.get(right)+1);
}else {
map.put(right, 1);
}
}
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
Integer count = (Integer) entry.getValue();
if(count%2==1) {
String index = (String) entry.getKey();
String[] split = index.split(",");
int a = Integer.parseInt(split[0]);
int b = Integer.parseInt(split[1]);
if(a<4&&a>=0&&b>=0&&b<4) {
if(A[a][b]==0) {
A[a][b] = 1;
}else {
A[a][b] = 0;
}
}
}
}
return A;
}
}