289. Game of Life

来源:互联网 发布:西安seo任兴华 编辑:程序博客网 时间:2024/05/22 03:27

主要难点在于inplace,解决办法:
用4种特殊state标记,同时记录下current state和next state。
标记如下:
00: current dead, next dead; 10: current dead, next live; 01: current live, next dead; 11: current live, next live;
tips:必须让最低位表示current,右数第二位表示next。这样的话,不管next定了没有,state % 2 都能取出当前状态

代码如下:

public class Solution {    public int f(int i, int j, int[][] board){        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length){            return -1;        }else{            return board[i][j];        }    }    public int liveNum(int i, int j, int[][] board){        int count = 0;        int[][] offsets = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1}};        for (int[] offset : offsets){            if (f(i + offset[0], j + offset[1], board) % 2 == 1)                count ++;        }        return count;    }    //00: current dead, next dead; 10: current dead, next live; 01: current live, next dead; 11: current live, next live;    //必须让最低位表示current,右数第二位表示next。这样的话,不管next定了没有,state % 2 都能取出当前状态    public void gameOfLife(int[][] board) {        if (board.length == 0 || board[0].length == 0)            return;        int count;        for(int i = 0; i < board.length; i ++){            for(int j = 0; j < board[0].length; j ++){                count = liveNum(i, j, board);                if (board[i][j] % 2 == 1){  //live cell                    if (count == 2 || count == 3)                        board[i][j] += 2;                }else{                    if (count == 3){                        board[i][j] += 2;                    }                }            }        }        for(int i = 0; i < board.length; i ++){            for(int j = 0; j < board[0].length; j ++){                board[i][j] = board[i][j] / 2;            }        }    }}
0 0
原创粉丝点击