题目
模拟法(原地)
普通解法没什么难度,需要另开一个数组,O(mn)
空间复杂度。原地算法:把之前死的后来活的,和之前活的后来死的标记一下,最后再处理一下即可。
class Solution
{
public:
void gameOfLife(vector<vector<int>> &board)
{
int m = board.size();
int n = board[0].size();
int dx[]{-1, -1, -1, 0, 0, 1, 1, 1};
int dy[]{-1, 0, 1, -1, 1, -1, 0, 1};
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
int count = 0;
for (int k = 0; k < 8; k++)
{
int x = i + dx[k];
int y = j + dy[k];
if (x >= 0 && x < m && y >= 0 && y < n)
{
count += (board[x][y] == 1 || board[x][y] == 3);
}
}
if (count == 3)
{
if (board[i][j] == 0)
board[i][j] = 2;
}
else if (count > 3 || count < 2)
{
if (board[i][j] == 1)
board[i][j] = 3;
}
}
}
for (auto &i : board)
{
for (auto &j : i)
{
if (j == 2)
j = 1;
else if (j == 3)
j = 0;
}
}
}
};