@@ -28,41 +28,23 @@ public void gameOfLife(int[][] board) {
28
28
int height = board .length ;
29
29
int width = board [0 ].length ;
30
30
int [][] next = new int [height ][width ];
31
+ int [][] directions = {{-1 , -1 }, {-1 , 0 }, {-1 , 1 }, {0 , 1 }, {1 , 1 }, {1 , 0 }, {1 , -1 }, {0 , -1 }};
31
32
32
33
for (int i = 0 ; i < board .length ; i ++) {
33
34
for (int j = 0 ; j < board [0 ].length ; j ++) {
34
35
int liveCellsCount = 0 ;
35
36
//count all its live cells
36
37
37
- if (j + 1 < width && board [i ][j + 1 ] == 1 ) {
38
- liveCellsCount ++;//right cell
39
- }
40
- if (j - 1 >= 0 && board [i ][j - 1 ] == 1 ) {
41
- liveCellsCount ++;//left cell
42
- }
43
- if (i + 1 < height && board [i + 1 ][j ] == 1 ) {
44
- liveCellsCount ++;//down cell
45
- }
46
- if (i - 1 >= 0 && board [i - 1 ][j ] == 1 ) {
47
- liveCellsCount ++;//up cell
48
- }
49
- if (i - 1 >= 0 && j - 1 >= 0 && board [i - 1 ][j - 1 ] == 1 ) {
50
- liveCellsCount ++;//up left cell
51
- }
52
- if (i - 1 >= 0 && j + 1 < width && board [i - 1 ][j + 1 ] == 1 ) {
53
- liveCellsCount ++;//up right cell
54
- }
55
- if (i + 1 < height && j - 1 >= 0 && board [i + 1 ][j - 1 ] == 1 ) {
56
- liveCellsCount ++;//down left cell
57
- }
58
- if (i + 1 < height && j + 1 < width && board [i + 1 ][j + 1 ] == 1 ) {
59
- liveCellsCount ++;//down right cell
38
+ for (int [] dir : directions ) {
39
+ int x = i + dir [0 ];
40
+ int y = j + dir [1 ];
41
+ if (x >= 0 && y >= 0 && x < height && y < width && board [x ][y ] == 1 ) {
42
+ liveCellsCount ++;
43
+ }
60
44
}
61
45
62
46
if (board [i ][j ] == 1 ) {
63
- if (liveCellsCount > 3 || liveCellsCount < 2 ) {
64
- next [i ][j ] = 0 ;
65
- } else {
47
+ if (liveCellsCount <= 3 && liveCellsCount >= 2 ) {
66
48
next [i ][j ] = 1 ;
67
49
}
68
50
} else if (board [i ][j ] == 0 ) {
0 commit comments