[leetcode]289. Game of Life
Analysis
2019年还没见过太阳,等一个晴天!!!—— [每天刷题并不难0.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.
Explanation:
题目意思比较简单,就是根据邻居中存活的的人数来判断每个点是否会继续存活下去或者死亡
Implement
solution 1: (这个是直接新开了一个数组,然后判断的)
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
vector<vector<int>> tmp(board);
int len = board.size();
int len1 = board[0].size();
for(int i=0; i<len; i++){
for(int j=0; j<len1; j++){
int cnt = 0;
for(auto d:dir){
int x=i+d[0], y=j+d[1];
if(alive(tmp, x, y, len, len1))
cnt++;
}
if((cnt < 2 || cnt >3) && board[i][j])
board[i][j] = 0;
else if(cnt == 3 && board[i][j]==0)
board[i][j] = 1;
}
}
}
bool alive(vector<vector<int>>& tmp, int x, int y, int len, int len1){
if(x>=0 && x<len && y>=0 && y<len1 && tmp[x][y])
return true;
return false;
}
private:
int dir[8][2] = {{1, 0}, {1, 1}, {1, -1}, {0, 1}, {0, -1}, {-1, 0}, {-1, 1}, {-1, -1}};
};
solution 2 (space complexity: O(1))
这个方法是没有另外开通数组,而是直接利用位运算符,每个位置的第0位表示当前状态,第一位表示更新后的状态,然后最后把每个点的状态右移一位就可以更新得到新的状态了~
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
int cnt = 0;
for(auto d:dir){
int x=i+d[0], y=j+d[1];
if(valid(x, y, m, n)){
if(board[x][y] & 1)
cnt++;
}
}
if(board[i][j] == 0){
if(cnt == 3)
board[i][j] |= 2;
}
else{
if(cnt < 2 || cnt > 3)
board[i][j] &= 1;
else
board[i][j] |= 2;
}
}
}
for(int i=0; i<m; i++){
for(int j=0; j<n; j++)
board[i][j] >>= 1;
}
}
bool valid(int x, int y, int len, int len1){
if(x>=0 && x<len && y>=0 && y<len1)
return true;
return false;
}
private:
int dir[8][2] = {{1, 0}, {1, 1}, {1, -1}, {0, 1}, {0, -1}, {-1, 0}, {-1, 1}, {-1, -1}};
};