289. Game of Life

来源:互联网 发布:mysql logbin日志查看 编辑:程序博客网 时间:2024/06/04 19:12

According to the Wikipedia's article: "The Game of Life, also known simply asLife, 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 statelive (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?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.



实现生命游戏。当邻居有两个生存时保持状态不变,当邻居有三个时变成生存状态,其他情况都灭亡。一开始是复制一个表来记录当前状态,原本的表记录更新后的状态。这样也能通过,但空间复杂度也为O(nm)。看discuss后知道,可以充分利用原表中每一个数中其余的位(因为本来只用了一位)。


代码:

class Solution0 {public:    void gameOfLife(vector<vector<int>>& board) {    int m = board.size(), n = board[0].size();    int xs[8] = {1, 1, 0, -1, -1, -1, 0, 1};    int ys[8] = {0, 1, 1, 1, 0, -1, -1, -1};        vector<vector<int>> dup(board);        for(int i = 0; i < m; ++i)        {        for(int j = 0; j < n; ++j)        {        int cnt = 0;        for(int k = 0; k < 8; ++k)        {        int x = j + xs[k], y = i + ys[k];        if(y < 0 || y >= m || x < 0 || x >= n)        continue;        cnt += dup[y][x];}if(cnt == 2) continue;if(cnt == 3) board[i][j] = 1;else board[i][j] = 0;}}    }};class Solution {public:    void gameOfLife(vector<vector<int>>& board) {    int m = board.size(), n = board[0].size();        for(int i = 0; i < m; ++i)        {        for(int j = 0; j < n; ++j)        {        int cnt = 0;        for(int y = max(i-1, 0); y <= min(i+1, m-1); ++y)        {        for(int x = max(j-1, 0); x <= min(j+1, n-1); ++x)        {        if(y == i && x == j) continue;        cnt += (board[y][x] & 1);}}if(cnt == 2) board[i][j] |= board[i][j]<<1;else if(cnt == 3) board[i][j] |= 2;}}for(int i = 0; i < m; ++i)        {        for(int j = 0; j < n; ++j)        {        board[i][j] >>= 1;}}    }};


原创粉丝点击