[leetcode-289]Game of Life(java)

问题描述:

分析:这道题起初自己搞复杂了,我原先以为是求最后的稳态,即一个状态再跳转到另外一个状态时,两个矩阵是一样的。但是有个测试用例是:
0 0 0 0 0
0 0 1 0 0
0 0 1 0 0
0 0 1 0 0
0 0 0 0 0
这个测试用例会发现该初始值根本就没有稳态,这才注意到是求的下一个状态。

然后这个题的难点就在于了如何在in-place里面存储改变后的值?(特别是followup中的,每次状态都会同时改变)。那就自定义了若干变量值,然后再修复即可

代码如下:1ms

public class Solution {
    private int countLiveNeigh(int[][] board,int row,int col){
        int count =  0;
        for(int i = row-1;i<=row+1;i++){
            for(int j = col-1;j<=col+1;j++){
                if(i==row && j==col)
                    continue;
                if(i>=0 && i<board.length && j>=0 && j<board[0].length && (board[i][j]==1||board[i][j]==2))//最开始状态为1的
                    count++;
            }
        }
        return count;
    }
    public void gameOfLife(int[][] board) {
        /*
        * 0:0--->0
          1:1--->1
          2:1--->0
          3:0--->1
        */
        int rowlen = board.length;
        int collen = board[0].length;
        for(int row = 0;row<rowlen;row++){
            for(int col = 0;col<collen;col++){
                int count = countLiveNeigh(board,row,col);
                if(count == 2);
                else if(count == 3){
                    board[row][col] = board[row][col]==0?3:1;
                }else{
                    board[row][col] = board[row][col]==1?2:0;
                }
            }
        }
        for(int row = 0;row<rowlen;row++){
            for(int col = 0;col<collen;col++){
                board[row][col] %= 2;
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值