leetcode -- Game of Life -- 有trick,要看
2015-12-10 20:21
274 查看
https://leetcode.com/problems/game-of-life/
参考http://bookshadow.com/weblog/2015/10/04/leetcode-game-life/
位运算(bit manipulation)
由于细胞只有两种状态0和1,因此可以使用二进制来表示细胞的生存状态
更新细胞状态时,将细胞的下一个状态用高位进行存储
全部更新完毕后,将细胞的状态右移一位
参考http://bookshadow.com/weblog/2015/10/04/leetcode-game-life/
位运算(bit manipulation)
由于细胞只有两种状态0和1,因此可以使用二进制来表示细胞的生存状态
更新细胞状态时,将细胞的下一个状态用高位进行存储
全部更新完毕后,将细胞的状态右移一位
class Solution(object): def gameOfLife(self, board): """ :type board: List[List[int]] :rtype: void Do not return anything, modify board in-place instead. """ dx = (1, 1, 1, 0, 0, -1, -1, -1) dy = (1, 0, -1, 1, -1, 1, 0, -1) for x in range(len(board)): for y in range(len(board[0])): lives = 0 for z in range(8): nx, ny = x + dx[z], y + dy[z] lives += self.getCellStatus(board, nx, ny) if lives + board[x][y] == 3 or lives == 3: # cell是live只有两种情况,neibor有3个live,i.e. lives == 3.或者neibor有2个live,并且原来是live,即01,所以加起来等于3. board[x][y] |= 2#给高位赋值1 for x in range(len(board)): for y in range(len(board[0])): board[x][y] >>= 1#右移到高位 def getCellStatus(self, board, x, y): if x < 0 or y < 0 or x >= len(board) or y >= len(board[0]): return 0 return board[x][y] & 1
相关文章推荐
- JavaScript—函数的定义和调用
- jQuery Easing 使用方法及其图解
- JavaScript模块化编程之require.js与sea.js
- week14---12月11日 JS内置对象——document文档对象、Dom对象
- ExtJS4为form表单必填项添加红色*标识
- CSS---定位
- Caffe 安装教程 (Mac OS)
- js中extends方法
- servlet打开一个jsp莫名乱码问题
- [Prufer] BZOJ 1211 [HNOI2004]树的计数
- poj 3398 Perfect Service 树形dp类似求树的点最小支配集
- 返回页面的数据中带标签,使js报错
- JSP与Servlet之间传值
- JavaScript 特殊之-prototype __proto__ class
- JSDOM对象控制HTML元素
- Caffe 深度学习框架上手教程
- JavaScript性能---加载及执行
- NodeJS 基本操作
- JS--for循环的性能优化
- Html中隐藏a标签