美团-棋子翻转-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); } } }
相关文章推荐
- 棋子翻转---- 美团2016研发工程师在线编程题
- 校招真题 美团 棋子翻转
- 美团 棋子翻转
- 牛客网---2016---美团棋子翻转
- 解答:名企笔试:美团2016校招(棋子翻转)
- 棋子翻转-java
- 算法类面试题解析——美团2016校招:棋子翻转
- 棋子翻转----美团2016研发工程师在线编程题
- JAVA面试题:棋子翻转
- java 单词翻转
- java中实现图片的水平翻转
- 每K个元素翻转一次链表,若最后剩余元素不足K个,不进行翻转(美团2014校招试题)
- java面试题之 使用两个int翻转字符串
- 【美团面试】java实现二维数组逆时针回形遍历
- 英文句子中单词翻转java实现
- JAVA用标准库自己写一个字符串翻转方法,翻转字符串中字母非单词
- java--整数翻转后相加
- 链表以k个一组进行翻转(2014美团研发笔试)
- java读取图片属性---判断手机拍照上传的图片是否被翻转
- 关于一道J笔试或者机试题的Java实现:从键盘输入一串字符,翻转后输出(要求不使用string相关类即对象)