LeetCode.289 Game of Life

来源:互联网 发布:ubuntu qq2012国际版 编辑:程序博客网 时间:2024/06/17 12:53

题目:

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):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. 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

  1. 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.
  2. 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) {        //著名的康威生命游戏,用1或者0代表生和死,且满足四种条件:        //1. 如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡        //2. 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活        //3. 如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡        //4. 如果死细胞周围正好有三个活细胞,则该位置死细胞复活        //题目要求:只在原地处理,不能另开辟空间,所以不能使用复制新数组加上外围全为0的方法处理。                //思路:用00(死->死),1(活-活),2(活->死),3(死->活)代表四种状态,处理完状态后,对整个数组状态%2操作,就只剩0(死)和1(活)了        //判断每个位置的周边包围的位置,采用八个方向数组:dir={{0,1},..,{1,1}}                int m=board.length;        int n=board[0].length;        int [][] dir={{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};                for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                //记数生的细胞                int count=0;                for(int [] d:dir){                    //需要判定坐标                    int x=d[0]+i;                    int y=d[1]+j;                    //判断是否超出边界                    if(x>=0&&x<m&&y>=0&&y<n&&(board[x][y]==1||board[x][y]==2)){                        //board[x][y]==1||board[x][y]==2 表示当前邻接的细胞还是活的,则记数+1                        count++;                     }                }                //统计完判断该细胞状态                if(board[i][j]==1&&(count<2||count>3)){                    //满足条件1,3                    board[i][j]=2;                }else if(board[i][j]==0&&count==3){                    //满足条件4                    board[i][j]=3;                }            }        }        //对矩阵进行%2        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                board[i][j]%=2;            }        }            }}


原创粉丝点击