leetcode面试准备: Game of Life

1 题目

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.

Follow up:

  • 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.
  • 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?

接口: public void gameOfLife(int[][] board)

2 思路

这是一种细胞自动机,每一个位置有两种状态,1为活细胞,0为死细胞,对于每个位置都满足如下的条件:

  1. 如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡
  2. 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活
  3. 如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡
  4. 如果死细胞周围正好有三个活细胞,则该位置死细胞复活

由于题目中要求我们用置换方法in-place来解题,所以我们就不能新建一个相同大小的数组,那么我们只能更新原有数组,但是题目中要求所有的位置必须被同时更新,但是在循环程序中我们还是一个位置一个位置更新的,那么当一个位置更新了,这个位置成为其他位置的neighbor时,我们怎么知道其未更新的状态呢,我们可以使用状态机转换:

  • 状态0: 死细胞转为死细胞
  • 状态1: 活细胞转为活细胞
  • 状态2: 活细胞转为死细胞
  • 状态3: 死细胞转为活细胞

最后我们对所有状态对2取余,那么状态0和2就变成死细胞,状态1和3就是活细胞,达成目的。我们先对原数组进行逐个扫描,对于每一个位置,扫描其周围八个位置,如果遇到状态1或2,就计数器累加1,扫完8个邻居,如果少于两个活细胞或者大于三个活细胞,而且当前位置是活细胞的话,标记状态2,如果正好有三个活细胞且当前是死细胞的话,标记状态3。完成一遍扫描后再对数据扫描一遍,对2取余变成我们想要的结果。

复杂度: Time: O(n) ; Space: O(1)

3 代码

      public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;
final int LIVE_TO_DEAD = 2;
final int DEAD_TO_LIVE = 3; for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int liveCell = getLiveCell(board, i, j);
if (board[i][j] == 1) {
if (liveCell < 2 || liveCell > 3) {
board[i][j] = LIVE_TO_DEAD;
}
} else {
if (liveCell == 3) {
board[i][j] = DEAD_TO_LIVE;
}
}
}
} for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = board[i][j] % 2;
}
}
} private int getLiveCell(int[][] board, int i, int j) {
int count = 0;
int row = i - 1;
int col = j - 1;
for (int p = row; p < row + 3; p++) {
for (int q = col; q < col + 3; q++) {
if ((p >= 0 && p < board.length)
&& (q >= 0 && q < board[0].length)) {
if (board[p][q] == 1 || board[p][q] == 2) {
count++;
}
}
}
}
count = count - board[i][j];
return count;
}

4 总结

中等难度。

leetcode面试准备: Game of Life的更多相关文章

  1. leetcode面试准备: Maximal Rectangle

    leetcode面试准备: Maximal Rectangle 1 题目 Given a 2D binary matrix filled with 0's and 1's, find the larg ...

  2. leetcode面试准备: Word Pattern

    leetcode面试准备: Word Pattern 1 题目 Given a pattern and a string str, find if str follows the same patte ...

  3. leetcode面试准备:Add and Search Word - Data structure design

    leetcode面试准备:Add and Search Word - Data structure design 1 题目 Design a data structure that supports ...

  4. leetcode面试准备:Reverse Words in a String

    leetcode面试准备:Reverse Words in a String 1 题目 Given an input string, reverse the string word by word. ...

  5. leetcode面试准备:Implement Trie (Prefix Tree)

    leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...

  6. leetcode面试准备:Triangle

    leetcode面试准备:Triangle 1 题目 Given a triangle, find the minimum path sum from top to bottom. Each step ...

  7. leetcode面试准备:Sliding Window Maximum

    leetcode面试准备:Sliding Window Maximum 1 题目 Given an array nums, there is a sliding window of size k wh ...

  8. leetcode面试准备:Simplify Path

    leetcode面试准备:Simplify Path 1 题目 Given an absolute path for a file (Unix-style), simplify it. For exa ...

  9. leetcode面试准备:Kth Largest Element in an Array

    leetcode面试准备:Kth Largest Element in an Array 1 题目 Find the kth largest element in an unsorted array. ...

随机推荐

  1. 深入了解webkit内核第一篇:JavaScript引擎深度解析

    看到HorkeyChen写的文章<[WebKit] JavaScriptCore解析--基础篇(三)从脚本代码到JIT编译的代码实现>,写的很好,深受启发.想补充一些Horkey没有写到的 ...

  2. 解决Redis Cluster模式下的排序问题

    通常的redis排序我们可以这么做: 比如按商品价格排序:sort goods_id_set by p_*_price 这样在非集群模式下是没问题的,但如果在集群模式下,就会报错: 说是在集群模式下不 ...

  3. .Net 程序集 签名工具sn.exe 密钥对SNK文件 最基本的用法

    阐述签名工具这个概念之前,我先说说它不是什么: 1.它不是用于给程序集加密的工具,它与阻止Reflector或ILSpy对程序集进行反编译一毛钱关系都没有. 2.它很讨厌人们把它和加密联系在一起. 我 ...

  4. Eclipse恢复初始界面&打开视图

    恢复初始界面: 单击菜单栏的windows主菜单,在子菜单里选择 Reset Perspective 会弹出各对话框 ,点 ok就可以了 打开视图:Windows->Show View 其中Ot ...

  5. 清橙OJ 1082 查找第K小元素 -- 快速排序

    题目地址:http://oj.tsinsen.com/A1082 问题描述 给定一个大小为n的数组s和一个整数K,请找出数组中的第K小元素. 这是一个补充程序的试题,你需要完成一个函数: int fi ...

  6. AD,Group

    DataTable dtUser = GetEmptyDT(); Dictionary<DirectoryEntry, string> test1 = GetUserAndGroup(cl ...

  7. 网站开发常用jQuery插件总结(一)提示插件alertify

    1.alertify插件功能 主要实现提示功能,用于代替js中的alert,confirm,prompt,显示友好的提示框 2.alertify官方地址 http://fabien-d.github. ...

  8. AVFoundation 初识

    AVFoundation是苹果 OS X系统和 iOS系统中用于处理基于时间的媒体数据的高级Objective-C框架. iOS中 AVFoundation 在整个体系中所处的角色

  9. Chrome 浏览器各版本下载大全

    随着最近64位版本的 Chrome 浏览器正式版的推出,Chrome 浏览器再次受到广大浏览迷的重点关注,今天我们就整理一下各版本的 Chrome 浏览器 32位及64位的下载地址,方便各位浏览迷选择 ...

  10. post请求json内容丢失问题

    今天在项目组用json传输数据 post方法提交 发现传输过去的数据json内的+ 号被直接干掉了. 后来传输之前直接先编码. 接收端: public void ProcessRequest(Http ...