Untitled

unknown
plain_text
7 months ago
1.5 kB
3
Indexable
Never
```class Solution {
private int n;
private int m;

public void gameOfLife(int[][] board) {
n = board.length;
m = board[0].length;
int[][] nextBoard = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
nextBoard[i][j] = shouldLive(board, i, j) ? 1 : 0;
}
}
for(int i = 0; i< n; i++){
for (int j = 0; j < m; j++){
board[i][j] = nextBoard[i][j];
}
}
}

private boolean shouldLive(int[][] board, int i, int j) {
int liveNeighborCount = countLiveNeighbors(board, i, j);
boolean isLive = board[i][j] == 1;
if (!isLive && liveNeighborCount == 3) {
return true;
} else if (isLive && (liveNeighborCount == 2 || liveNeighborCount == 3)) {
return true;
}
return false;
}

private int countLiveNeighbors(int[][] board, int i, int j) {
int count = 0;
int rowStart = i - 1 >= 0 ? i - 1 : i;
int rowEnd = i + 1 < n ? i + 1 : i;
int colStart = j - 1 >= 0 ? j - 1 : j;
int colEnd = j + 1 < m ? j + 1 : j;

for (int row = rowStart; row <= rowEnd; row++) {
for (int col = colStart; col <= colEnd; col++) {
if (row == i && col == j) {
continue;
}

if (board[row][col] == 1) {
count++;
}
}
}
return count;
}
}```