-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathGameOfLife.java
79 lines (79 loc) · 2.52 KB
/
GameOfLife.java
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package io.ziheng.array.leetcode;
/**
* LeetCode 289. Game of Life
* https://leetcode.com/problems/game-of-life/
*/
public class GameOfLife {
private int[][] directions = new int[][] {
{ 0, 1, },
{ 0, -1, },
{ 1, 0, },
{-1, 0, },
{ 1, 1, },
{-1, -1, },
{ 1, -1, },
{-1, 1, },
};
public void gameOfLife(int[][] board) {
if (board == null || board.length == 0) {
return;
}
int[][] newBoard = new int[board.length][board[0].length];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
int cellState = board[i][j];
int cellsAround = findLiveCellsAround(i, j, board);
if (cellState == 1
&& cellsAround < 2) {
newBoard[i][j] = 0;
} else if (cellState == 1
&& cellsAround >= 2
&& cellsAround <= 3) {
newBoard[i][j] = 1;
} else if (cellState == 1
&& cellsAround > 3) {
newBoard[i][j] = 0;
} else if (cellState == 0
&& cellsAround == 3) {
newBoard[i][j] = 1;
} else {
newBoard[i][j] = 0;
}
}
}
fillBoard(newBoard, board);
}
private void fillBoard(int[][] newBoard, int[][] board) {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = newBoard[i][j];
}
}
}
// private int[][] copyBoard(int[][] board) {
// int[][] newBoard = new int[board.length][board[0].length];
// for (int i = 0; i < board.length; i++) {
// for (int j = 0; j < board[i].length; j++) {
// newBoard[i][j] = board[i][j];
// }
// }
// return newBoard;
// }
private int findLiveCellsAround(int x, int y, int[][] board) {
int cnt = 0;
for (int[] direction : directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if (isVaild(nextX, nextY, board)
&& board[nextX][nextY] == 1) {
cnt++;
}
}
return cnt;
}
private boolean isVaild(int x, int y, int[][] board) {
return x >= 0 && x < board.length
&& y >= 0 && y < board[x].length;
}
}
/* EOF */