题目:
代码(首刷自解 2024年3月27日):
class Solution {
public:
int judge(vector<vector<int>>& board, int row, int col)//活返回true
{
int top = row - 1, bottom = row + 1, left = col - 1, right = col + 1;
// 判断边界
if (top < 0) top = 0;
if (bottom > board.size() - 1) bottom = board.size() - 1;
if (left < 0) left = 0;
if (right > board[0].size() - 1) right = board[0].size() - 1;
// 计算周围数量
int alive_cell_count = 0;
if (board[row][col] == 1) --alive_cell_count;
for (int i = top; i <= bottom; ++i)
{
for (int j = left; j <= right; ++j)
{
if (board[i][j] == 1)
{
alive_cell_count++;
}
}
}
// 根据规则返回死/活
return alive_cell_count;
}
void gameOfLife(vector<vector<int>>& board) {
int m = board.size();
int n = board[0].size();
vector<vector<int>> newboard(m, vector<int>(n, 0));
// 遍历数组
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
// 判断周围状态,得到下一状态(另一数组)
int count = judge(board, i, j);
if (board[i][j] == 1 && (count == 2 || count == 3))
newboard[i][j] = 1;
if (board[i][j] == 0 && count == 3)
newboard[i][j] = 1;
}
}
// 旧数组 = 新数组
board = newboard;
}
};