当前位置:
首页 >
leetcode 289. Game of Life | 289. 生命游戏(Java)
发布时间:2024/2/28
48
豆豆
生活随笔
收集整理的这篇文章主要介绍了
leetcode 289. Game of Life | 289. 生命游戏(Java)
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
题目
https://leetcode.com/problems/game-of-life/
题解
首先,遍历整个棋盘,如果是 1,就将上下左右的 count 值加 1。
然后,没有任何技巧,就是根据 count 值,拆 if-else。
如果要原地操作的话,可以使用位运算,一个 int 有 32 bit,输入数据只用了一个 bit,所以我们可以利用其他空闲的bit位进行“原地修改”。本文不再详述,可参考:https://leetcode-cn.com/problems/game-of-life/solution/c-wei-yun-suan-yuan-di-cao-zuo-ji-bai-shuang-bai-b/
class Solution {public void gameOfLife(int[][] board) {int M = board.length;int N = board[0].length;int[][] cnt = new int[M][N];for (int i = 0; i < M; i++) {for (int j = 0; j < N; j++) {if (board[i][j] == 1) {if (i > 0) cnt[i - 1][j]++;if (j > 0) cnt[i][j - 1]++;if (i > 0 && j > 0) cnt[i - 1][j - 1]++;if (i < M - 1) cnt[i + 1][j]++;if (j < N - 1) cnt[i][j + 1]++;if (i < M - 1 && j < N - 1) cnt[i + 1][j + 1]++;if (i < M - 1 && j > 0) cnt[i + 1][j - 1]++;if (i > 0 && j < N - 1) cnt[i - 1][j + 1]++;}}}for (int i = 0; i < M; i++) {for (int j = 0; j < N; j++) {if (board[i][j] == 1 && cnt[i][j] < 2 || cnt[i][j] > 3) board[i][j] = 0;if (board[i][j] == 0 && cnt[i][j] == 3) board[i][j] = 1;}}} }总结
以上是生活随笔为你收集整理的leetcode 289. Game of Life | 289. 生命游戏(Java)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: leetcode 363. Max Su
- 下一篇: leetcode 299. Bulls