Description

Given aboardwithmbyncells, each cell has an initial statelive(1) ordead(0). Each cell interacts with itseight 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?

Hint

不用new一个新的matrix, 如果当前的点会改变, 就用一个新的值来记录即可, 如果本来是0, 下一步活了, 就记录为3(3 % 2 =1), 如果本来是1, 下一步死了, 就记录为2(2 % 2 = 0), 其他的值只要知道3代表0, 2代表1即可

##Train of Thought

##Code

        **public class Solution {

**

            public void gameOfLife\(int\[\]\[\] board\) {

                if \(board == null \|\| board.length == 0 \|\| board\[0\].length == 0\) {

                    return;

                }



                int\[\] x = {0, 0, 1, -1, 1, 1, -1, -1};

                int\[\] y = {1, -1, 0, 0, 1, -1, 1, -1};



                for \(int i = 0; i < board.length; i++\) {

                    for \(int j = 0; j < board\[0\].length; j++\) {

                        int count = 0;

                        for \(int k = 0; k < x.length; k++\) {

                            int newX = i + x\[k\];

                            int newY = j + y\[k\];

                            if \(newX >= 0 && newX < board.length && newY >= 0 && newY <board\[0\].length && \(board\[newX\]\[newY\] == 1 \|\| board\[newX\]\[newY\] == 2\)\) {

                                count++;

                            }

                        }

                        if \(board\[i\]\[j\] == 1 && \(count < 2 \|\| count > 3\)\) {

                            board\[i\]\[j\] = 2;

                        }

                        if \(board\[i\]\[j\] == 0 && count == 3\) {

                            board\[i\]\[j\] = 3;

                        }

                    }

                }



                for \(int i = 0; i < board.length; i++\) {

                    for \(int j = 0; j < board\[0\].length; j++\) {

                        board\[i\]\[j\] = board\[i\]\[j\] % 2;

                    }

                }



            }

        }

##Complexity

results matching ""

    No results matching ""