LeetCode Game of Life 解题

来源:互联网 发布:tensorflow 1.2 whl 编辑:程序博客网 时间:2024/05/16 11:06

1. 非原地的解答,通过四周补0可以很自然的按照规则写出下一代的状态

Game of Life


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?



class Solution {public:    void gameOfLife(vector<vector<int>>& board) {                if (board.size() == 0 || board[0].size() == 0) return;                size_t m = board.size();        size_t n = board[0].size();        vector<vector<int> > b;                vector<int> first(n+2,0);        b.push_back(first);                for (size_t ii = 0; ii < m; ++ii) {            vector<int> r(n+2,0);            for (size_t jj = 0; jj < n; ++jj) {                r[jj+1] = board[ii][jj];            }            b.push_back(r);        }                vector<int> last(n+2,0);        b.push_back(last);         for (size_t i = 1; i < m+1; ++i) {            for (size_t j = 1; j < n+1; ++j) {               int nei = b[i-1][j-1]+b[i-1][j]+b[i-1][j+1]+b[i][j-1]+b[i][j+1]+b[i+1][j-1]+b[i+1][j]+b[i+1][j+1];               if (nei < 2) {                   board[i-1][j-1] = 0;               } else if ((nei == 2 || nei == 3) && board[i-1][j-1] == 1) {                   board[i-1][j-1] = 1;               } else if (nei == 3 && board[i-1][j-1] == 0) {                   board[i-1][j-1] = 1;               } else if (nei > 3 && board[i-1][j-1] == 1) {                   board[i-1][j-1] = 0;               }            }        }            }};


0 0
原创粉丝点击