289. Game of Life
Game of Life
Solution
public class Solution {
public void gameOfLife(int[][] board) {
if (board == null || board.length == 0) return;
int row = board.length;
int column = board[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
int life = getLiveNeighbours(board, row, column, i, j);
if ((board[i][j] & 1) == 1) {
if (life < 2) {
//dead
} else if (life == 2 || life == 3) {
board[i][j] = board[i][j] | (1 << 1);
} else if (life > 3) {
// dead
}
} else {
if (life == 3) {
board[i][j] = board[i][j] | (1 << 1);
}
}
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
board[i][j] = board[i][j] >> 1;
}
}
}
private int getLiveNeighbours(int[][] board, int row, int column, int x, int y) {
int result = 0;
if (isValid(row, column, x - 1, y - 1) && (board[x - 1][y - 1] & 1) == 1) {
result++;
}
if (isValid(row, column, x, y - 1) && (board[x][y - 1] & 1) == 1) {
result++;
}
if (isValid(row, column, x + 1, y - 1) && (board[x + 1][y - 1] & 1) == 1) {
result++;
}
if (isValid(row, column, x - 1, y) && (board[x - 1][y] & 1) == 1) {
result++;
}
if (isValid(row, column, x + 1, y) && (board[x + 1][y] & 1) == 1) {
result++;
}
if (isValid(row, column, x - 1, y + 1) && (board[x - 1][y + 1] & 1) == 1) {
result++;
}
if (isValid(row, column, x, y + 1) && (board[x][y + 1] & 1) == 1) {
result++;
}
if (isValid(row, column, x + 1, y + 1) && (board[x + 1][y + 1] & 1) == 1) {
result++;
}
return result;
}
private boolean isValid(int row, int column, int x, int y) {
return x >= 0 && x < row && y >= 0 && y < column;
}
}Last updated