LeetCode 289. 生命游戏 (读题然后模拟实现)
原题链接
简单
作者:
JustDoIt11
,
2024-03-16 14:48:12
,
所有人可见
,
阅读 9
class Solution {
// 周围的8个方向
final static int[] dx = new int[] {-1, -1, -1, 0, 0, 1, 1, 1};
final static int[] dy = new int[] {-1, 0, 1, -1, 1, -1, 0, 1};
boolean[][] alive;
public boolean check(int[][] board, int x, int y) {
int cnt = 0;
for (int i = 0; i < 8; i ++ ) {
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= board.length || b < 0 || b >= board[0].length) continue;
if (board[a][b] == 0) continue;
cnt ++ ;
}
if (board[x][y] == 1 && cnt < 2) return false;
if (board[x][y] == 1 && (cnt == 2 || cnt == 3)) return true;
if (board[x][y] == 1 && cnt > 3) return false;
if (board[x][y] == 0 && cnt == 3) return true;
return false;
}
public void gameOfLife(int[][] board) {
alive = new boolean[board.length][board[0].length];
for (int i = 0; i < board.length; i ++ ) {
for (int j = 0; j < board[0].length; j ++ ) {
alive[i][j] = check(board, i, j);
}
}
for (int i = 0; i < board.length; i ++ ) {
for (int j = 0; j < board[0].length; j ++ ) {
if (alive[i][j]) board[i][j] = 1;
else board[i][j] = 0;
}
}
}
}