Game of Life
Thoughts
Code
class Solution {
public void gameOfLife(int[][] board) {
int[][] dirs = new int[][]{{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
int m = board.length, n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int lives = 0;
for (int[] dir : dirs) {
int x = i + dir[0];
int y = j + dir[1];
if (x >= 0 && x < m && y >= 0 && y < n) {
if (board[x][y] == 1 || board[x][y] == 2) {
lives++;
}
}
}
if (board[i][j] == 1 && (lives < 2 || lives > 3)) {
board[i][j] = 2;
} else if (board[i][j] == 0 && lives == 3) {
board[i][j] = 3;
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] % 2 == 0) {
board[i][j] = 0;
} else {
board[i][j] = 1;
}
}
}
}
}Analysis
Last updated