lc287 Game of Live

难点在于不能使用额外的空间。

观察到数组中每一个元素要么为1要么为0,32位int只用了一位,可以利用bit操作,将第二次state存储到int变量的倒数第二位中。例:board[i][j] = 3, 换成二进制就是一堆0最后两位是11,表达的含义就是当前状态cell为live,下一次状态还是live。

1) 如何更新第一次state 直接把board[i][j]右移一位即可,这样就把第一次state更新为第二次state

2) 如何更新第二次state 需要统计当前cell周围存活cell的数量,注意可能写code的时候边缘cell会导致数组越界,要添加判断条件Math.max(0, i-1), Math.max(0, j-1), Max.min(m, i+1), Math.max(n, j+1) 然后就可以按照规则更新第二次state,注意由于更新第一次state时使用的是右移操作,所以第二次state的默认值为0,就是说我们只需要处理第二次state为1的情况即可。

代码如下:

 class Solution {
public void gameOfLife(int[][] board) {
if(board == null || board.length == 0)
return; int m = board.length;
int n = board[0].length; for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
int lives = count(board, m, n, i, j); if(board[i][j] == 1 && lives >= 2 && lives <= 3)
board[i][j] = 3;
else if(board[i][j] == 0 && lives == 3)
board[i][j] = 2;
}
} for(int i = 0; i < m; ++i){
for(int j = 0; j < n; ++j){
board[i][j] >>= 1;
}
}
} private int count(int[][] board, int m, int n, int i, int j){
int count = 0; for(int a = Math.max(0, i-1); a <= Math.min(m - 1, i+1); a++){
for(int b = Math.max(0, j-1); b <= Math.min(n-1, j+1); b++){
count += board[a][b] & 1;
}
} count -= board[i][j] & 1;
return count;
}
}

lc287 Game of Live的更多相关文章

随机推荐

  1. windows10 家庭版 无法远程2012的解决

    windows 10安装最新补丁后无法远程windows server 2008.2012服务器 报错信息如下:出现身份验证错误,要求的函数不受支持  可能是由于CredSSP加密Oracle修正. ...

  2. csp-s模拟测试10.1(b)X 国的军队,排列组合, 回文题解

    题面:https://www.cnblogs.com/Juve/articles/11615883.html X 国的军队: 好像有O(T*N)的直接贪心做法 其实多带一个log的二分也可以过 先对所 ...

  3. 字符串+dp——cf1163D好题

    很好的题(又复习了一波kmp) /* dp[i,j,k]:到s1的第i位,匹配s2到j,s3到k的最优解 */ #include<bits/stdc++.h> using namespac ...

  4. 【源码】PyObject_VAR_HEAD 定长对象 变长对象

    PyObject_VAR_HEAD      Python-3.7.4\Include\object.h   /* PyObject_VAR_HEAD defines the initial segm ...

  5. iOS之CGcontext.h方法和属性简介

    /* CoreGraphics - CGContext.h Copyright (c) 2000-2012 Apple Inc. All rights reserved. */ #ifndef CGC ...

  6. PAT甲级——A1097 Deduplication on a Linked List

    Given a singly linked list L with integer keys, you are supposed to remove the nodes with duplicated ...

  7. idea怎么打war包

    1.上方导航栏粥找到 Buid——> Bild Artifacts... 2.弹出框中选择 3.war包打好啦,一般放在编译的 target目录下

  8. enctype="multipart/form-data"的form传参

    1.jsp <li class="btns"><input id="btnImport" class="btn btn-primar ...

  9. js 实现音频播放与暂停

    html: <script src="js/jquery-2.1.3.min.js"></script> <div id="soundIco ...

  10. HBase Ganglia