Skip to content

Commit af5470d

Browse files
author
Yi Gu
committed
[Array] Add a solution to Game of Lift
1 parent d426fcb commit af5470d

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Array/GameLife.swift

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/game-of-life/
3+
* Primary idea: Divide whole things to 4 cases, change 1 to 2 and 0 to 3 to avoid
4+
* overrite issues, and then use %2 to get final results
5+
*
6+
* Time Complexity: O(n), Space Complexity: O(1)
7+
*
8+
*/
9+
10+
class GameLife {
11+
func gameOfLife(_ board: inout [[Int]]) {
12+
guard board.count > 0 else {
13+
return
14+
}
15+
16+
let m = board.count, n = board[0].count
17+
18+
for i in 0 ..< m {
19+
for j in 0 ..< n {
20+
changeStatus(&board, i, j, m, n)
21+
}
22+
}
23+
24+
board = board.map { $0.map { $0 % 2 } }
25+
}
26+
27+
private func changeStatus(_ board: inout [[Int]], _ i: Int, _ j: Int, _ m: Int, _ n: Int) {
28+
var liveNum = 0
29+
30+
for x in i - 1 ... i + 1 {
31+
for y in j - 1 ... j + 1 {
32+
if x < 0 || x >= m || y < 0 || y >= n {
33+
continue
34+
}
35+
if x == i && y == j {
36+
continue
37+
}
38+
39+
liveNum = board[x][y] == 1 || board[x][y] == 2 ? liveNum + 1 : liveNum
40+
}
41+
}
42+
43+
if board[i][j] == 1 {
44+
if liveNum < 2 || liveNum > 3 {
45+
board[i][j] = 2
46+
}
47+
} else {
48+
if liveNum == 3 {
49+
board[i][j] = 3
50+
}
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)