1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| class Solution { public void gameOfLife(int[][] board) { int m = board.length; if (m == 0) { return; } int n = board[0].length; if (n == 0) { return; } int[][] directions = new int[][]{{-1, 0}, {-1, -1}, {-1, 1}, {0, 1}, {0, -1}, {1, 0}, {1, -1}, {1, 1}}; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { int sum = 0; for (int k = 0; k < 8; k++) { int newX = i + directions[k][0]; int newY = j + directions[k][1]; if (newX >= 0 && newX < m && newY < n && newY >= 0 && (board[newX][newY] == 1||board[newX][newY] == -1)) { sum += 1; } } if (board[i][j] == 1 && (sum < 2 || sum > 3)) { board[i][j] = -1; } if (board[i][j] == 0 && sum == 3) { board[i][j] = 2; } } }
for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] > 0) { board[i][j] = 1; } else { board[i][j] = 0; } } } } }
|