题目来源
一道状态转移的题目,题目比较长…然后实际做起来并不难。我一开始做利用了mn的空间,然后处理起来比较冗长。
代码如下:
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int rows = board.size();
if (rows == 0)
return;
int cols = board[0].size();
vector<vector<int>> neighbors(rows, vector<int>(cols, 0));
for (int row=0; row<rows; row++)
for (int col=0; col<cols; col++) {
if (board[row][col] == 1) {
if (row > 0)
neighbors[row-1][col]++;
if (row > 0 && col > 0)
neighbors[row-1][col-1]++;
if (col > 0)
neighbors[row][col-1]++;
if (row < rows - 1 && col > 0)
neighbors[row+1][col-1]++;
if (row < rows - 1)
neighbors[row+1][col]++;
if (row < rows - 1 && col < cols - 1)
neighbors[row+1][col+1]++;
if (col < cols - 1)
neighbors[row][col+1]++;
if (row > 0 && col < cols - 1)
neighbors[row-1][col+1]++;
}
}
for (int row=0; row<rows; row++)
for (int col=0; col<cols; col++) {
if (board[row][col] == 1 && (neighbors[row][col] < 2 || neighbors[row][col] > 3))
board[row][col] = 0;
if (board[row][col] == 0 && neighbors[row][col] == 3)
board[row][col] = 1;
}
}
};
然后原来感觉这种题不值得写东西的,但是看了大神们简洁的代码,觉得还是得写一下学习一下,以后这种隔壁八块,判断是否越界的,可以这么写,然后判断是哪个状态的,直接用与或这些操作来判断,简洁的很,厉害,实在是佩服。见代码:
class Solution {
public:
void gameOfLife(vector<vector<int>>& board) {
int rows = board.size(), cols = (rows == 0) ? 0 : board[0].size();
for (int row=0; row<rows; row++)
for (int col=0; col<cols; col++) {
int cnt = 0;
for (int i=max(0, row-1); i<=min(rows-1, row+1); i++)
for (int j=max(0, col-1); j<=min(cols-1, col+1); j++)
cnt += board[i][j] & 1;
if (cnt == 3 || cnt - board[row][col] == 3)
board[row][col] |= 2;
}
for (int row=0; row<rows; row++)
for (int col=0; col<cols; col++)
board[row][col] >>= 1;
}
};