leetcode 289. Game of Life | 289. 生命游戏(Java)
生活随笔
收集整理的這篇文章主要介紹了
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