-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Expand file tree
/
Copy pathGameofLife.java
More file actions
54 lines (49 loc) · 1.88 KB
/
GameofLife.java
File metadata and controls
54 lines (49 loc) · 1.88 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
// Time Complexity : O(m * n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
// Your code here along with comments explaining your approach
/*
We create a function to basically check all neighbours at 8 directions(if applicable) and apply the given
problem's rules of live and dead cell count for each entry in the board.To make sure we are not counting
recently alive or ignoring recently dead cells, we mark them with 2 and 3 and later revert them in-place
to their actual states in the board.
*/
class Solution {
private int[][] dirs = new int[][]{{0, 1} , {1, 0} , {0, -1} , {-1, 0}, {-1, -1}, {-1, 1}, {1, 1}, {1, -1}};
public void gameOfLife(int[][] board) {
int m = board.length;
int n = board[0].length;
for(int i = 0 ; i < m ; i++) {
for(int j = 0 ; j < n ; j++) {
checkIfAlive(board, m , n, i , j);
}
}
// 1 -> 2 (previous alive, now dead)
// 0 -> 3 (previous dead, now alive)
for(int i = 0 ; i < m ; i++) {
for(int j = 0 ; j < n ; j++) {
if(board[i][j] == 2)
board[i][j] = 0;
else if(board[i][j] == 3)
board[i][j] = 1;
}
}
}
private void checkIfAlive(int[][] board, int m, int n, int i , int j) {
int countLiveCell = 0;
for(int[] dir : dirs) {
int x = i + dir[0];
int y = j + dir[1];
if(x < 0 || y < 0 || x > m - 1 || y > n - 1)
continue;
if(board[x][y] == 1 || board[x][y] == 2)
countLiveCell++;
}
if(board[i][j] == 0 && countLiveCell == 3)
board[i][j] = 3;
else if(board[i][j] == 1 && (countLiveCell < 2 || countLiveCell > 3)) {
board[i][j] = 2;
}
}
}