原题网址:https://leetcode.com/problems/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):
Write a function to compute the next state (after one update) of the board given its current state.
Follow up:
方法:将下一状态保存在高一位比特。
public class Solution { public void gameOfLife(int[][] board) { int right = board[0].length-1; int bottom = board.length-1; for(int i=0; i<board.length; i++) { for(int j=0; j<board[i].length; j++) { int live = 0; for(int io=-1; io<=1; io++) { for(int jo=-1; jo<=1; jo++) { if (io==0 && jo==0) continue; int row = i+io, col = j+jo; if (row>=0 && row<board.length && col>=0 && col<board[row].length && (board[row][col]&1)==1) live ++; } } if ((board[i][j]&1) == 1) { if (2 <= live && live <= 3) board[i][j] |= 0b10; } else { if (live == 3) board[i][j] |= 0b10; } } } for(int i=0; i<board.length; i++) { for(int j=0; j<board[i].length; j++) { board[i][j] >>= 1; } } } }
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。