leetcode 289. Game of Life

来源:互联网 发布:淘宝iphone7可信度 编辑:程序博客网 时间:2024/06/08 14:33

leetcode 289. Game of Life

谷歌的面试题果然很开眼界,比如这题,用两bit来表示前后两次的状态,很巧妙。

public class Solution {    public void gameOfLife(int[][] board) {        if(board==null||board.length==0) return;        int m = board.length;        int n = board[0].length;        // if(n==0) return;        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                int lives = getlivesaround(board,m,n,i,j);                if(board[i][j]==1&&(lives==2||lives==3)){                    board[i][j] = 3; // 11<-01                }                if(board[i][j]==0&&lives==3){                    board[i][j] = 2;  // 10<-00                }            }        }        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                board[i][j] = board[i][j]>>1;            }        }            }        private int getlivesaround(int[][] board, int m, int n, int i, int j){        int lives = 0;        for(int h = Math.max(i-1,0);h <= Math.min(i+1, m-1);h++){            for(int k = Math.max(j-1,0);k <= Math.min(j+1, n-1);k++){                lives += board[h][k]&1;            }        }        lives -= board[i][j]&1;        return lives;    }}


原创粉丝点击