題目來源
一道狀態(tài)轉(zhuǎn)移的題目抵知,題目比較長(zhǎng)…然后實(shí)際做起來并不難堤魁。我一開始做利用了mn的空間耕魄,然后處理起來比較冗長(zhǎng)晨川。
代碼如下:
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;
}
}
};
然后原來感覺這種題不值得寫東西的证九,但是看了大神們簡(jiǎn)潔的代碼删豺,覺得還是得寫一下學(xué)習(xí)一下,以后這種隔壁八塊愧怜,判斷是否越界的呀页,可以這么寫,然后判斷是哪個(gè)狀態(tài)的叫搁,直接用與或這些操作來判斷赔桌,簡(jiǎn)潔的很供炎,厲害渴逻,實(shí)在是佩服。見代碼:
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;
}
};