289. Game of Life
来源:互联网 发布:西安seo任兴华 编辑:程序博客网 时间:2024/05/22 03:27
主要难点在于inplace,解决办法:
用4种特殊state标记,同时记录下current state和next state。
标记如下:
00: current dead, next dead; 10: current dead, next live; 01: current live, next dead; 11: current live, next live;
tips:必须让最低位表示current,右数第二位表示next。这样的话,不管next定了没有,state % 2 都能取出当前状态
代码如下:
public class Solution { public int f(int i, int j, int[][] board){ if (i < 0 || i >= board.length || j < 0 || j >= board[0].length){ return -1; }else{ return board[i][j]; } } public int liveNum(int i, int j, int[][] board){ int count = 0; int[][] offsets = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {-1, -1}, {1, -1}, {1, 1}, {-1, 1}}; for (int[] offset : offsets){ if (f(i + offset[0], j + offset[1], board) % 2 == 1) count ++; } return count; } //00: current dead, next dead; 10: current dead, next live; 01: current live, next dead; 11: current live, next live; //必须让最低位表示current,右数第二位表示next。这样的话,不管next定了没有,state % 2 都能取出当前状态 public void gameOfLife(int[][] board) { if (board.length == 0 || board[0].length == 0) return; int count; for(int i = 0; i < board.length; i ++){ for(int j = 0; j < board[0].length; j ++){ count = liveNum(i, j, board); if (board[i][j] % 2 == 1){ //live cell if (count == 2 || count == 3) board[i][j] += 2; }else{ if (count == 3){ board[i][j] += 2; } } } } for(int i = 0; i < board.length; i ++){ for(int j = 0; j < board[0].length; j ++){ board[i][j] = board[i][j] / 2; } } }}
0 0
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- 289. Game of Life
- HDU 1171 Big Event in HDU 多重背包 .
- 项目1-星号拼字母
- 深入理解Java的接口和抽象类
- 双目相机的畸变校正以及平行校正(极线校正)的入门问题总结
- Unity学习笔记(三)----Space Shooter
- 289. Game of Life
- Octave使用所遇到的问题
- 内核态和用户态的区别
- 傅里叶变换与小波变换
- Jetty-为web应用添加网页
- 第十二天
- vsync, hsync, VBLANK
- Linux(1)
- DVD