[LeetCode] 289. Game of Life

生命游戏。题意是给一个board,上面所有的元素表示细胞,细胞的死或活用0或1表示。并且有如下规则,对于每个细胞周围的八个细胞,

1. 如果小于两个活细胞,则当前细胞死亡;

2. 如果有两个或者三个活细胞,则当前细胞存活;

3. 如果大于三个活细胞,则当前细胞死亡;

4. 如果当前细胞死亡但是周围有三个活细胞,则当前细胞可以复活;

根据如上规则请更新这个board的存活情况。要求是in-place做。

思路没有什么特别的,但是这个题又是数组但是要求不使用额外空间。不用额外空间的题目还有73题。这个题因为要求是in-place做所以在不能创造额外空间的情况下,只能通过一个叫做状态机的东西来记录每个cell的状态改变。这里我再次引用grandyang大神的解释

状态0: 死细胞转为死细胞

状态1: 活细胞转为活细胞

状态2: 活细胞转为死细胞

状态3: 死细胞转为活细胞

最后对所有状态对2取余,则状态0和2就变成死细胞,状态1和3就是活细胞,达成目的。先对原数组进行逐个扫描,对于每一个位置,扫描其周围八个位置,如果遇到状态1或2,就计数器累加1,扫完8个邻居,如果少于两个活细胞或者大于三个活细胞,而且当前位置是活细胞的话,标记状态2,如果正好有三个活细胞且当前是死细胞的话,标记状态3。完成一遍扫描后再对数据扫描一遍,对2取余变成我们想要的结果。

按照这个思路就可以写代码了。需要遍历input两次,第一次需要遍历input的每一个cell,先算出每个cell周围的八个cell有几个是活的,以得出当前cell的存活情况。如果当前cell经计算可以存活,标记成2;如果不能存活,标记成3。第二次遍历的时候对2取余变成我们想要的结果。

时间O(mn)

空间O(1)

 1 /**
 2  * @param {number[][]} board
 3  * @return {void} Do not return anything, modify board in-place instead.
 4  */
 5 var gameOfLife = function (board) {
 6     for (let i = 0; i < board.length; i++) {
 7         for (let j = 0; j < board[0].length; j++) {
 8             let liveCells = count(board, i, j);
 9             if (board[i][j] === 1 && (liveCells < 2 || liveCells > 3)) {
10                 board[i][j] = 2;
11             }
12             if (board[i][j] === 0 && liveCells === 3) {
13                 board[i][j] = 3;
14             }
15         }
16     }
17 
18     for (let i = 0; i < board.length; i++) {
19         for (let j = 0; j < board[0].length; j++) {
20             board[i][j] %= 2;
21         }
22     }
23 };
24 
25 let count = function (board, i, j) {
26     let count = 0;
27     let indexes = [[1, -1], [1, 0], [1, 1], [0, -1], [0, 1], [-1, -1], [-1, 0], [-1, 1]];
28     for (let index of indexes) {
29         if (index[0] + i < 0 || index[0] + i > board.length - 1 || index[1] + j < 0 || index[1] + j > board[0].length - 1) continue;
30         if (board[index[0] + i][index[1] + j] === 1 ||
31             board[index[0] + i][index[1] + j] === 2) count++;
32     }
33     return count;
34 };

猜你喜欢

转载自www.cnblogs.com/aaronliu1991/p/12310574.html