1. 程式人生 > >leetcode學習筆記36

leetcode學習筆記36

289. Game of Life

According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”

Given a board with m by n cells, each cell has an initial state live (1) or dead (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

Any live cell with fewer than two live neighbors dies, as if caused by under-population.
Any live cell with two or three live neighbors lives on to the next generation.
Any live cell with more than three live neighbors dies, as if by over-population…
Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.

Example:

Input:
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]

這主要採用了二進位制的演算法
參考https://leetcode.com/problems/game-of-life/discuss/73223/Easiest-JAVA-solution-with-explanation
主要用到了&1,取第一位,>>1,移除第一位

class Solution {
    public void gameOfLife(int[][] board) {
        for
(int i=0;i<board.length;i++){ for(int j=0;j<board[i].length;j++){ int lives=0; for(int m=Math.max(0, i-1);m<=Math.min(board.length-1, i+1);m++) { for(int n=Math.max(0, j-1);n<=Math.min(board[i].length-1, j+1);n++) { lives+=board[m][n]&1; } } lives-=board[i][j]&1; 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<board.length;i++){ for(int j=0;j<board[i].length;j++){ board[i][j]>>=1; } } } }