Skip to content

Commit 4f275a5

Browse files
game of life
1 parent 69779a7 commit 4f275a5

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

MEDIUM/src/medium/GameOfLife.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package medium;
2+
3+
public class GameOfLife {
4+
public void gameOfLife(int[][] board) {
5+
int height = board.length, width = board[0].length;
6+
int[][] next = new int[height][width];
7+
8+
for(int i = 0; i < board.length; i++){
9+
for(int j = 0; j < board[0].length; j++){
10+
int liveCellsCount = 0;
11+
//count all its live cells
12+
13+
if(j+1 < width && board[i][j+1] == 1) liveCellsCount++;//right cell
14+
if(j-1 >= 0 && board[i][j-1] == 1) liveCellsCount++;//left cell
15+
if(i+1 < height && board[i+1][j] == 1) liveCellsCount++;//down cell
16+
if(i-1 >= 0 && board[i-1][j] == 1) liveCellsCount++;//up cell
17+
if(i-1 >= 0 && j-1 >= 0 && board[i-1][j-1] == 1) liveCellsCount++;//up left cell
18+
if(i-1 >= 0 && j+1 < width && board[i-1][j+1] == 1) liveCellsCount++;//up right cell
19+
if(i+1 < height && j-1 >= 0 && board[i+1][j-1] == 1) liveCellsCount++;//down left cell
20+
if(i+1 < height && j+1 < width && board[i+1][j+1] == 1) liveCellsCount++;//down right cell
21+
22+
if(board[i][j] == 1){
23+
if(liveCellsCount > 3 || liveCellsCount < 2) {
24+
next[i][j] = 0;
25+
} else {
26+
next[i][j] = 1;
27+
}
28+
} else if(board[i][j] == 0) {
29+
if(liveCellsCount == 3){
30+
next[i][j] = 1;
31+
}
32+
}
33+
}
34+
}
35+
36+
for(int i = 0; i < board.length; i++){
37+
for(int j = 0; j < board[0].length; j++){
38+
board[i][j] = next[i][j];
39+
}
40+
}
41+
}
42+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
|301|[Remove Invalid Parentheses](https://leetcode.com/problems/remove-invalid-parentheses/)|[Solution]| ? | ? | Hard| BFS
2323
|299|[Bulls and Cows](https://leetcode.com/problems/bulls-and-cows/)|[Solution](../../blob/master/EASY/src/easy/BullsandCows.java)| O(n)|O(1) | Easy|
2424
|292|[Nim Game](https://leetcode.com/problems/nim-game/)|[Solution](../../blob/master/EASY/src/easy/NimGame.java)| O(1)|O(1) | Easy|
25+
|289|[Game of Life](https://leetcode.com/problems/game-of-life/)|[Solution](../../blob/master/MEDIUM/src/medium/GameOfLife.java)| O(m*n)|O(m*n), could be optimized to O(1) | Medium|
2526
|283|[Move Zeroes](https://leetcode.com/problems/move-zeroes/)|[Solution](../../blob/master/EASY/src/easy/MoveZeroes.java)| O(n)|O(1) | Easy|
2627
|280|[Wiggle Sort](https://leetcode.com/problems/wiggle-sort/)|[Solution](../../blob/master/MEDIUM/src/medium/WiggleSort.java)| O(n)|O(1) | Medium|
2728
|278|[First Bad Version](https://leetcode.com/problems/first-bad-version/)|[Solution](../../blob/master/EASY/src/easy/FirstBadVersion.java)| O(logn)|O(1) | Easy| Binary Search

0 commit comments

Comments
 (0)