Skip to content

Commit e1d872f

Browse files
refactor 289
1 parent 5350d07 commit e1d872f

File tree

1 file changed

+28
-26
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+28
-26
lines changed

src/main/java/com/fishercoder/solutions/_289.java

Lines changed: 28 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -24,40 +24,42 @@ Write a function to compute the next state (after one update) of the board given
2424
border of the array. How would you address these problems?*/
2525

2626
public class _289 {
27-
public void gameOfLife(int[][] board) {
28-
int height = board.length;
29-
int width = board[0].length;
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}};
27+
public static class Solution1 {
28+
public void gameOfLife(int[][] board) {
29+
int height = board.length;
30+
int width = board[0].length;
31+
int[][] next = new int[height][width];
32+
int[][] directions = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}};
3233

33-
for (int i = 0; i < board.length; i++) {
34-
for (int j = 0; j < board[0].length; j++) {
35-
int liveCellsCount = 0;
36-
//count all its live cells
34+
for (int i = 0; i < board.length; i++) {
35+
for (int j = 0; j < board[0].length; j++) {
36+
int liveCellsCount = 0;
37+
//count all its live cells
3738

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++;
39+
for (int[] dir : directions) {
40+
int x = i + dir[0];
41+
int y = j + dir[1];
42+
if (x >= 0 && y >= 0 && x < height && y < width && board[x][y] == 1) {
43+
liveCellsCount++;
44+
}
4345
}
44-
}
4546

46-
if (board[i][j] == 1) {
47-
if (liveCellsCount <= 3 && liveCellsCount >= 2) {
48-
next[i][j] = 1;
49-
}
50-
} else if (board[i][j] == 0) {
51-
if (liveCellsCount == 3) {
52-
next[i][j] = 1;
47+
if (board[i][j] == 1) {
48+
if (liveCellsCount <= 3 && liveCellsCount >= 2) {
49+
next[i][j] = 1;
50+
}
51+
} else if (board[i][j] == 0) {
52+
if (liveCellsCount == 3) {
53+
next[i][j] = 1;
54+
}
5355
}
5456
}
5557
}
56-
}
5758

58-
for (int i = 0; i < board.length; i++) {
59-
for (int j = 0; j < board[0].length; j++) {
60-
board[i][j] = next[i][j];
59+
for (int i = 0; i < board.length; i++) {
60+
for (int j = 0; j < board[0].length; j++) {
61+
board[i][j] = next[i][j];
62+
}
6163
}
6264
}
6365
}

0 commit comments

Comments
 (0)