|
| 1 | +/** |
| 2 | + * 289. Game of Life |
| 3 | + * https://leetcode.com/problems/game-of-life/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular |
| 7 | + * automaton devised by the British mathematician John Horton Conway in 1970." |
| 8 | + * |
| 9 | + * The board is made up of an m x n grid of cells, where each cell has an initial state: live |
| 10 | + * (represented by a 1) or dead (represented by a 0). Each cell interacts with its eight neighbors |
| 11 | + * (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia |
| 12 | + * article): |
| 13 | + * 1. Any live cell with fewer than two live neighbors dies as if caused by under-population. |
| 14 | + * 2. Any live cell with two or three live neighbors lives on to the next generation. |
| 15 | + * 3. Any live cell with more than three live neighbors dies, as if by over-population. |
| 16 | + * 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. |
| 17 | + * |
| 18 | + * The next state of the board is determined by applying the above rules simultaneously to every |
| 19 | + * cell in the current state of the m x n grid board. In this process, births and deaths occur |
| 20 | + * simultaneously. |
| 21 | + * |
| 22 | + * Given the current state of the board, update the board to reflect its next state. |
| 23 | + * |
| 24 | + * Note that you do not need to return anything. |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * @param {number[][]} board |
| 29 | + * @return {void} Do not return anything, modify board in-place instead. |
| 30 | + */ |
| 31 | +var gameOfLife = function(board) { |
| 32 | + const directions = [[1, -1], [1, 0], [1, 1], [0, -1], [0, 1], [-1, -1], [-1, 0], [-1, 1]]; |
| 33 | + const r = board.length; |
| 34 | + const c = board[0].length; |
| 35 | + |
| 36 | + for (let i = 0; i < r; i++) { |
| 37 | + for (let j = 0; j < c; j++) { |
| 38 | + let lives = 0; |
| 39 | + for (const d of directions) { |
| 40 | + if (d[0] + i < 0 || d[0] + i >= r || d[1] + j < 0 || d[1] + j >= c) { |
| 41 | + continue; |
| 42 | + } else if (board[d[0] + i][d[1] + j] === 1 || board[d[0] + i][d[1] + j] === 2) { |
| 43 | + lives++; |
| 44 | + } |
| 45 | + } |
| 46 | + if (board[i][j] === 0 && lives === 3) { |
| 47 | + board[i][j] = 3; |
| 48 | + } else if (board[i][j] === 1 && (lives < 2 || lives > 3)) { |
| 49 | + board[i][j] = 2; |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + for (let i = 0; i < r; i++) { |
| 55 | + for (let j = 0; j < c; j++) { |
| 56 | + board[i][j] %= 2; |
| 57 | + } |
| 58 | + } |
| 59 | +}; |
0 commit comments