您的位置:首页 > 编程语言 > Java开发

美团-棋子翻转-Java

2017-07-07 21:10 691 查看
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.junit.Test;

/**
* 题目描述 在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]]
*
* @author 崔洪振367
* @version 创建时间:2017年7月7日 下午1:01:55
*/
public class 棋子翻转 {
/**
* 解题思路:
* 1、声明一个HashMap,<String , Integer>
* 2、遍历翻转数组,求出每个节点对应的四个节点位置,以字符串形式保存到hashmap键中,出现次数保存到值中
* 3、遍历HashMap,修改原棋盘
*/
HashMap<String, Integer> hashMap = null;

@Test
public void test(){
int[][] A = {{0,0,1,1},{1,0,1,0},{0,1,1,0},{0,0,1,0}};
int[][] f = {{2,2},{3,3},{4,4}};
int[][] result = flipChess(A, f);
for(int i=0; i<result.length; i++){
for(int j=0; j<result[0].length; j++){
System.out.print(result[i][j] + ",");
}
System.out.println();
}
}

public int[][] flipChess(int[][] A, int[][] f) {
hashMap = new HashMap<>();

int aLen = A.length;
int aaLen = A[0].length;

// 遍历翻转的矩阵,找出四个点的坐标
for (int i = 0; i < f.length; i++) {// 题目中f.length的大小为3
int point0 = f[i][0];
int point1 = f[i][1];
String hmKey = "";
//上
if ((point0 - 1) > 0 && (point0 - 1) <= aLen && point1 > 0 && point1 <= aaLen) {
hmKey = (point0-1)+","+point1;
addElementToHashMap(hashMap, hmKey);
}
//下
if ((point0+1) > 0 && (point0+1) <= aLen && point1 > 0 && point1 <= aaLen) {
hmKey = (point0+1)+","+point1;
addElementToHashMap(hashMap, hmKey);
}
//左
if (point0 > 0 && point0 <= aLen && (point1-1) > 0 && (point1-1) <= aaLen) {
hmKey = point0+","+(point1-1);
addElementToHashMap(hashMap, hmKey);
}
//右
if (point0 > 0 && point0 <= aLen && (point1+1) > 0 && (point1+1) <= aaLen) {
hmKey = point0+","+(point1+1);
addElementToHashMap(hashMap, hmKey);
}
}

//遍历HashMap,修改原棋盘
Iterator<Entry<String, Integer>> iterator =  hashMap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, Integer> entry = (Entry<String, Integer>) iterator.next();
int v = entry.getValue();
String k = entry.getKey();
//System.out.println("key:"+k+","+"value:"+v);
if(v%2!=0){
String[] p = k.split(",");
int x = Integer.parseInt(p[0]);
int y = Integer.parseInt(p[1]);
A[x-1][y-1] = A[x-1][y-1]==0?1:0;
}
}
return A;
}

public void addElementToHashMap(HashMap<String, Integer> hp, String fz) {
if (hashMap.containsKey(fz)) {
int value = hashMap.get(fz);
hashMap.put(fz, value+1);
} else {
hashMap.put(fz, 1);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: