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):
- 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.
解答:
方法很巧妙。原来是一位的,这里用两位来存储。
新 <- 旧
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
- Game of Life
- Game Of Life
- LeetCode:Game of Life
- LeetCode: Game of Life
- Game of Life
- leetcode289 : Game of Life
- 【LeetCode】Game of Life
- Game of Life
- Game of Life
- LeetCode Game of Life
- Leetcode Game of Life
- Game of Life
- Game of Life
- [289]Game of Life
- [LeetCode] Game of Life
- Game Of Life
- LeetCode -- Game of Life
- 【leetcode】Game of Life
- Resource(一 OverView)
- 正则表达式中多行匹配问题
- java大数据学习笔记(四) 并发集合
- leetcode15.3Sum
- maven操作命令
- Game of Life
- java 获取MP3文件时长等信息
- leetcode笔记:Merge Two Sorted Lists
- cocoa pods 安装 WebViewJavascriptBridge 简明使用
- Mysql之各种各样的函数啦
- Mac装matlab2015b步骤
- 安卓app设计规范
- 微软2016年4月实习生笔试第一题-font size题解
- VS2010 专业版 报错:error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏