289. 生命游戏
- 题号:289
- 来源:LeetCode
- 难度:中等
- 标签:
数组矩阵模拟 - 语言:TypeScript
- 解法:2 个
- 作者:lmliheng
- 最近更新:2026-09-27
解法一
TypeScript · O(m*n) 时间 · O(1) 空间 · 更新于 2026-09-27
用 -1/2 标记死亡与复活,两轮原地更新
typescript
/**
* @difficulty medium
* @tags 数组,矩阵,模拟
* @time O(m*n)
* @space O(1)
* @note 用 -1/2 标记死亡与复活,两轮原地更新
* @289. 生命游戏
*/
function gameOfLife(board: number[][]): void {
const m = board.length;
const n = board[0].length;
// 统计活邻居数量(安全写法)
const countLives = (x: number, y: number): number => {
let lives = 0;
for (let i = x - 1; i <= x + 1; i++) {
for (let j = y - 1; j <= y + 1; j++) {
if (
i >= 0 && i < m &&
j >= 0 && j < n &&
!(i === x && j === y) &&
(board[i][j] === 1 || board[i][j] === -1)
) {
lives++;
}
}
}
return lives;
};
// 第一轮:标记状态
// 1 → 0 : -1
// 0 → 1 : 2
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const lives = countLives(i, j);
if (board[i][j] === 1) {
if (lives < 2 || lives > 3) {
board[i][j] = -1; // 原来活,现在死
}
} else {
if (lives === 3) {
board[i][j] = 2; // 原来死,现在活
}
}
}
}
// 第二轮:还原成 0 / 1
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === -1) board[i][j] = 0;
if (board[i][j] === 2) board[i][j] = 1;
}
}
}解法二 · TypeScript
TypeScript · O(m*n) 时间 · O(1) 空间 · 更新于 2026-09-27
与解法一相同,中间状态标记后再还原
typescript
/**
* @difficulty medium
* @tags 数组,矩阵,模拟
* @time O(m*n)
* @space O(1)
* @note 与解法一相同,中间状态标记后再还原
* @289. 生命游戏(解法二)
*/
function gameOfLife(board: number[][]): void {
const m = board.length;
const n = board[0].length;
// 统计活邻居数量(安全写法)
const countLives = (x: number, y: number): number => {
let lives = 0;
for (let i = x - 1; i <= x + 1; i++) {
for (let j = y - 1; j <= y + 1; j++) {
if (i >= 0 && i < m &&
j >= 0 && j < n &&
!(i === x && j === y) &&
(board[i][j] === 1 || board[i][j] === -1)) {
lives++;
}
}
}
return lives;
};
// 第一轮:标记状态
// 1 → 0 : -1
// 0 → 1 : 2
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
const lives = countLives(i, j);
if (board[i][j] === 1) {
if (lives < 2 || lives > 3) {
board[i][j] = -1; // 原来活,现在死
}
}
else {
if (lives === 3) {
board[i][j] = 2; // 原来死,现在活
}
}
}
}
// 第二轮:还原成 0 / 1
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (board[i][j] === -1)
board[i][j] = 0;
if (board[i][j] === 2)
board[i][j] = 1;
}
}
}源码:ts/leetcode/289. 生命游戏(解法二).ts
在 GitHub 上查看题目所在目录:lmliheng/algorithm