# 289.Game-of-Life

## 289. Game of Life

## 题目地址

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

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?
```

## 代码

### Approach 1: O(1) Space Solution

```java
class Solution {
  public void gameOfLife(int[][] board) {
    int[] neighbors = {0, 1, -1};
    int R = board.length;
    int C = board[0].length;

    for (int row = 0; row < R; row++) {
      for (int col = 0; col < C; col++) {
        int liveNeighbors = 0;
        for (int i = 0; i < 3; i++) {
          for (int j = 0; j < 3; j++) {
            if (!(neighbors[i] == 0 && neighbors[j] == 0)) {
              int r = row + neighbors[i];
              int c = col + neighbors[j];

              if ((r < R && r >= 0) && (c < C && c >= 0) && (Math.abs(board[r][c]) == 1))) {
                liveNeighbors += 1;
              }
            }
          }
        }
        // Rule 1 or Rule 3 and Rule 2
        if ((board[row][col] == 1) && (liveNeighbors < 2 || liveNeighbors > 3)) {
          board[row][col] = -1;
        } 
        // Rule 4
        if (board[row][col] == 0 && liveNeighbors == 3) {
         // 2 signifies the cell is now live but was originally dead.
          board[row][col] = 2;
        }
      }
    }

    // Get the final representation for the newly updated board.
    for (int row = 0; row < rows; row++) {
        for (int col = 0; col < cols; col++) {
            if (board[row][col] > 0) {
                board[row][col] = 1;
            } else {
                board[row][col] = 0;
            }
        }
    }
  }
}
```

### Approach 2: O(mn) Space Solution

```java
class Solution {
  public void gameOfLife(int[][] board) {
     int[] neighbors = {0, 1, -1};
    int R = board.length;
    int C = board[0].length;

    int[][] copyBoard = new int[R][C];

    for (int row = 0; row < R; row++) {
      for (int col = 0; col < C; col++) {
        copyBoard[row][col] = board[row][col];
      }
    }

    for (int row = 0; row < R; row++) {
      for (int col = 0; col < C; col++) {
        int liveNeighbors = 0;

        for (int i = 0; i < 3; i++) {
          for (int j = 0; j < 3; j++) {
            if (!(neighbors[i] == 0 && neighbors[j] == 0)) {
              int r = (row + neighbors[i]);
              int c = (col + neighbors[j]);

              if ((r < R && r >= 0) && (c < C && c >= 0) && (copyBoard[r][c] == 1)) {
                liveNeighbors += 1;
              }
            }
          }    
        }

        // Rule 1 or Rule 3 (and Rule 2)
        if ((copyBoard[row][col] == 1) && (liveNeighbors < 2 || liveNeighbors > 3)) {
          board[row][col] = 0;
        }

        // Rule 4
        if (copyBoard[row][col] == 0 && liveNeighbors == 3) {
          board[row][col] = 1;
        }
      }
    }
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/graph-search/289.game-of-life.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
