289. Game of Life
Posted apanda009
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了289. Game of Life相关的知识,希望对你有一定的参考价值。
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?
编解码法
复杂度
时间 O(NN) 空间 O(1)
思路
最简单的方法是再建一个矩阵保存,不过当inplace解时,如果我们直接根据每个点周围的存活数量来修改当前值,由于矩阵是顺序遍历的,这样会影响到下一个点的计算。如何在修改值的同时又保证下一个点的计算不会被影响呢?实际上我们只要将值稍作编码就行了,因为题目给出的是一个int矩阵,大有空间可以利用。这里我们假设对于某个点,值的含义为
[2nd bit, 1st bit] = [next state, current state]
- 00 dead (next) <- dead (current)
- 01 dead (next) <- live (current)
- 10 live (next) <- dead (current)
- 11 live (next) <- live (current)
To get the current state, simply do
board[i][j] & 1
To get the next state, simply do
board[i][j] >> 1
更多的follow up 请见 http://www.cnblogs.com/EdwardLiu/p/5079920.html
public class Solution { int[][] directions = new int[][]{{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}}; public void gameOfLife(int[][] board) { if (board==null || board.length==0 || board[0].length==0) return; int m = board.length; int n = board[0].length; for (int i=0; i<m; i++) { for (int j=0; j<n; j++) { int lives = 0; for (int[] dir : directions) { int x = i + dir[0]; int y = j + dir[1]; if (x>=0 && x<m && y>=0 && y<n) { if ((board[x][y] & 1) == 1) lives++; } } //update board[i][j] if (board[i][j] == 0) { if (lives == 3) board[i][j] = 2; else board[i][j] = 0; } else { //board[i][j] == 1 if (lives<2 || lives>3) board[i][j] = 1; else board[i][j] = 3; } } } //decode for (int i=0; i<m; i++) { for (int j=0; j<n; j++) { board[i][j] >>= 1; } } } }
以上是关于289. Game of Life的主要内容,如果未能解决你的问题,请参考以下文章