Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit393cee9

Browse files
refactor 289
1 parenta6583d0 commit393cee9

File tree

1 file changed

+73
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+73
-0
lines changed

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

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
publicclass_289 {
44
publicstaticclassSolution1 {
5+
/**
6+
* Time: O(m*n)
7+
* Space: O(m*n)
8+
*/
59
publicvoidgameOfLife(int[][]board) {
610
intheight =board.length;
711
intwidth =board[0].length;
@@ -40,4 +44,73 @@ public void gameOfLife(int[][] board) {
4044
}
4145
}
4246
}
47+
48+
publicstaticclassSolution2 {
49+
/**
50+
* Time: O(m*n)
51+
* Space: O(1)
52+
* <p>
53+
* we use different numbers to represent its previous state so that we can change in place without losing track of its previous state
54+
* we define:
55+
* live to dead is 1 -> -1
56+
* dead to live is 0 -> 2
57+
* live to live is 1 -> 1
58+
* <p>
59+
* Credit: Solution 2 from https://leetcode.com/problems/game-of-life/solution/
60+
*/
61+
publicvoidgameOfLife(int[][]board) {
62+
// Neighbors array to find 8 neighboring cells for a given cell
63+
int[]neighbors = {0,1, -1};
64+
65+
introws =board.length;
66+
intcols =board[0].length;
67+
68+
// Iterate through board cell by cell.
69+
for (introw =0;row <rows;row++) {
70+
for (intcol =0;col <cols;col++) {
71+
72+
// For each cell count the number of live neighbors.
73+
intliveNeighbors =0;
74+
75+
for (inti =0;i <3;i++) {
76+
for (intj =0;j <3;j++) {
77+
78+
if (!(neighbors[i] ==0 &&neighbors[j] ==0)) {
79+
intr = (row +neighbors[i]);
80+
intc = (col +neighbors[j]);
81+
82+
// Check the validity of the neighboring cell.
83+
// and whether it was originally a live cell.
84+
if ((r <rows &&r >=0) && (c <cols &&c >=0) && (Math.abs(board[r][c]) ==1)) {
85+
liveNeighbors +=1;
86+
}
87+
}
88+
}
89+
}
90+
91+
// Rule 1 or Rule 3
92+
if ((board[row][col] ==1) && (liveNeighbors <2 ||liveNeighbors >3)) {
93+
// -1 signifies the cell is now dead but originally was live.
94+
board[row][col] = -1;
95+
}
96+
// Rule 4
97+
if (board[row][col] ==0 &&liveNeighbors ==3) {
98+
// 2 signifies the cell is now live but was originally dead.
99+
board[row][col] =2;
100+
}
101+
}
102+
}
103+
104+
// Get the final representation for the newly updated board.
105+
for (introw =0;row <rows;row++) {
106+
for (intcol =0;col <cols;col++) {
107+
if (board[row][col] >0) {
108+
board[row][col] =1;
109+
}else {
110+
board[row][col] =0;
111+
}
112+
}
113+
}
114+
}
115+
}
43116
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp