Game of Life

来源:互联网 发布:766冒险岛数据库 编辑:程序博客网 时间:2024/06/15 19:42

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

  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.

解答:

方法很巧妙。原来是一位的,这里用两位来存储。

新 <- 旧

1  <-  0

1  <-  1

因此用0,1,10,11四种状态来表达每个方格中的状态。

最后把每个数除以10得到的就是新的状态值。

// new <- old//  1  <- 1//  1  <- 0// 00, 01 is not changed.thus use 0,1,10,11 to represent the labelclass Solution {public:    int LiveNum(vector<vector<int>> b,int x,int y){        int c = 0;        for(int p = x-1; p <=x+1; p++)        for(int q = y-1; q <=y+1; q++){            if(p<0 || q<0 || p>=b.size() || q>=b[0].size() || (p == x && q == y))                continue;            else{                if(b[p][q]%10 == 1)                c++;            }        }        return c;    }    void gameOfLife(vector<vector<int>>& board) {        if(board.size()==0 || board[0].size() == 0)        return;        for(int i = 0; i < board.size(); i++)        for(int j = 0; j < board[0].size(); j++){            int x=LiveNum(board,i,j);            if(board[i][j] == 0){                if(x == 3)                    board[i][j] += 10;            }else if(board[i][j] == 1){                if(x == 2 || x == 3)                    board[i][j] += 10;            }        }                for(int i = 0; i < board.size(); i++)        for(int j = 0; j < board[0].size(); j++)            board[i][j] /= 10;    }};


0 0
原创粉丝点击