289. Game of Life
来源:互联网 发布:java rmi exp 编辑:程序博客网 时间:2024/06/06 18:15
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.
Follow up:
Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
class Solution { public void gameOfLife(int[][] board) { if(board.length<=0) return; int row = board.length; int col = board[0].length; for(int i=0;i<row;i++) { for(int j = 0; j<col; j++) { int x = getLiveNum(board, i, j); if(board[i][j] == 0) {//died cell if(x == 3) board[i][j]+=10; }else {//live cell if(x == 2 || x == 3) board[i][j]+=10; } } } for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { if(board[i][j] /10 ==1) board[i][j] = 1; else board[i][j] = 0; } } } public int getLiveNum(int[][] board, int x, int y) { int count = 0; for(int i= x-1; i<=x+1;i++) { for(int j= y-1;j<=y+1;j++) { if(i<0 || j<0 || i>=board.length || j>=board[0].length || (i==x && j==y)) continue; if(board[i][j] %10 == 1) count++; } } return count; } }
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 比较两个对象的属性变化
- Linux 基础操作(六)————TOP、进程管理及用户登录审计
- Spring知识整理【四】Spring AOP
- 10月10日~10月17 产品资讯
- Structured Streaming 实现思路与实现概述
- 289. Game of Life
- leetcode_java_第二题 ReserveInteger
- C/C++中的基本数据类型
- MongoDB replset 配置
- 编程模式(schema) —— 表驱动法(table-driven)
- tableau应用实战笔记
- 2017.10.10队内互测——高校模拟赛
- 插入排序
- c语言——字母塔