|
| 1 | +package leetcode; |
| 2 | + |
| 3 | +/** |
| 4 | + * Project Name : Leetcode |
| 5 | + * Package Name : leetcode |
| 6 | + * File Name : GameofLife |
| 7 | + * Creator : Leo |
| 8 | + * Description : 289. Game of Life |
| 9 | + */ |
| 10 | +public class GameofLife { |
| 11 | + |
| 12 | + /** |
| 13 | + * 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): |
| 14 | +
|
| 15 | + Any live cell with fewer than two live neighbors dies, as if caused by under-population. |
| 16 | + Any live cell with two or three live neighbors lives on to the next generation. |
| 17 | + Any live cell with more than three live neighbors dies, as if by over-population.. |
| 18 | + Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. |
| 19 | + Write a function to compute the next state (after one update) of the board given its current state. |
| 20 | +
|
| 21 | + time : O(m * n) |
| 22 | + space : O(1) |
| 23 | +
|
| 24 | + * @param board |
| 25 | + */ |
| 26 | + |
| 27 | + public void gameOfLife(int[][] board) { |
| 28 | + if (board == null || board.length == 0) return; |
| 29 | + int m = board.length; |
| 30 | + int n = board[0].length; |
| 31 | + for (int i = 0; i < m; i++) { |
| 32 | + for (int j = 0; j < n; j++) { |
| 33 | + int count = countNeighbor(board, i, j); |
| 34 | + if (board[i][j] == 1) { |
| 35 | + if (count == 2 || count == 3) { |
| 36 | + board[i][j] += 2; |
| 37 | + } |
| 38 | + } else if (count == 3) { |
| 39 | + board[i][j] += 2; |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + for (int i = 0; i < m; i++) { |
| 44 | + for (int j = 0; j < n; j++) { |
| 45 | + board[i][j] = board[i][j] >> 1; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private int countNeighbor(int[][] board, int i, int j) { |
| 51 | + int count = 0; |
| 52 | + for (int row = Math.max(0, i - 1); row <= Math.min(i + 1, board.length - 1); row++) { |
| 53 | + for (int col = Math.max(0, j - 1); col <= Math.min(j + 1, board[0].length - 1); col++) { |
| 54 | + if (row == i && col == j) continue; |
| 55 | + if ((board[row][col] & 1) == 1) count++; |
| 56 | + } |
| 57 | + } |
| 58 | + return count; |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments