Leetcode 289. Game of Life

33 篇文章 0 订阅
30 篇文章 0 订阅

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]
]

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?

tag: array

method 1

因为是同时发生的,所以不能先修改一部分,再去修改一部分,后面的数会受之前的修改影响,因此,不如使用一个数组,提前存储每个元素活邻居的数量。

使用一个dp数组,记录每个元素的活邻居

  • 1.少于两个活邻居的活细胞将死去

  • 2.有两个活邻居或三个活邻居的活细胞能够继续活下去

  • 3.任何有3三个以上的活邻居的活细胞将死去

  • 4.有三个活邻居的死细胞能够复活

    public void gameOfLife(int[][] board) {
    int[][] dp = new int[board.length][board[0].length];

          for (int i = 0; i < board.length; i++) {
              for (int j = 0; j < board[0].length; j++) {
                  dp[i][j] += searchLive(board,i-1,j-1)+searchLive(board,i-1,j)+searchLive(board,i-1,j+1);
                  dp[i][j] += searchLive(board,i,j-1) + searchLive(board,i,j+1);
                  dp[i][j] += searchLive(board,i+1,j-1)+searchLive(board,i+1,j)+searchLive(board,i+1,j+1);
              }
          }
    
          for (int i = 0; i < board.length; i++) {
              for (int j = 0; j < board[0].length; j++) {
                  //live cell
                  if (board[i][j] == 1){
                      if (dp[i][j] < 2)
                          board[i][j] = 0;
                      else if (dp[i][j] > 3)
                          board[i][j] = 0;
                  }else{
                      if (dp[i][j] == 3)
                          board[i][j] = 1;
                  }
              }
          }
    
          System.out.println(Arrays.toString(board));
      }
    
      public int searchLive(int[][] dp, int i, int j){
          if (i == -1 || j == -1 || i == dp.length || j == dp[0].length)
              return 0;
    
          if (dp[i][j] == 0)
              return 0;
          else return 1;
      }
    

method 2

O(1)的space,既然无法借助额外空间,那么只能在数组本身标记,思考发现本题中只会有两个数0,1,因此可以用其他数字来代表修改状态,第二次遍历时将这些数字修改回0,1即可

更优秀的解法,通过位操作,解决了O(n)的空间问题

  • 因为总共就四种状态0-》0(00),0-》1(10),1-》0(01),1-》1(11)

  • 只需考虑10和11,即复活和保持生存,对应于十进制分别是2和3

  • 巧妙地将原本的0和1值与代表转换的四个状态的值对应起来,非常smart

    //https://leetcode.com/problems/game-of-life/discuss/73223/Easiest-JAVA-solution-with-explanation
    public void gameOfLife2(int[][] board) {
    if (board == null || board.length == 0) return;
    int m = board.length, n = board[0].length;

          for (int i = 0; i < m; i++) {
              for (int j = 0; j < n; j++) {
                  int lives = liveNeighbors(board, m, n, i, j);
    
                  // In the beginning, every 2nd bit is 0;
                  // So we only need to care about when will the 2nd bit become 1.
                  if (board[i][j] == 1 && lives >= 2 && lives <= 3) {
                      board[i][j] = 3; // Make the 2nd bit 1: 01 ---> 11
                  }
                  if (board[i][j] == 0 && lives == 3) {
                      board[i][j] = 2; // Make the 2nd bit 1: 00 ---> 10
                  }
              }
          }
    
          for (int i = 0; i < m; i++) {
              for (int j = 0; j < n; j++) {
                  board[i][j] >>= 1;  // Get the 2nd state.
              }
          }
      }
    
      public int liveNeighbors(int[][] board, int m, int n, int i, int j) {
          int lives = 0;
          for (int x = Math.max(i - 1, 0); x <= Math.min(i + 1, m - 1); x++) {
              for (int y = Math.max(j - 1, 0); y <= Math.min(j + 1, n - 1); y++) {
                  lives += board[x][y] & 1;
              }
          }
          lives -= board[i][j] & 1;
          return lives;
      }
    

summay

  1. 提前使用一个数组存储原始信息,防干扰
  2. 要保证O(1)的space,可考虑对原数组位置上进行标记,标记的数不能和原来的数冲突
  3. 使用Math.max/min来判断边界,减少if
  4. method 2 中还考虑了有几种状态,从而使用位操作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值