classSolution { public: voidgameOfLife(vector<vector<int>>& board){ int dx[] = {-1, -1, -1, 0, 1, 1, 1, 0}; int dy[] = {-1, 0, 1, 1, 1, 0, -1, -1}; int n = board.size(), m = board[0].size(); for (int x = 0; x < n; ++x) { for (int y = 0; y < m; ++y) { int cnt = 0; for (int i = 0; i < 8; ++i) { int nx = x + dx[i], ny = y + dy[i]; if (0 <= nx && nx < n && 0 <= ny && ny < m && (board[nx][ny]&1)) { cnt++; } } if (board[x][y] == 1) { board[x][y] += ((cnt == 2 || cnt == 3) << 1); } else { board[x][y] += ((cnt == 3) << 1); } } } for (int x = 0; x < n; ++x) { for (int y = 0; y < m; ++y) { board[x][y] >>= 1; } } } };
python
classSolution: defgameOfLife(self, board: List[List[int]]) -> None: dx = [-1, -1, -1, 0, 1, 1, 1, 0] dy = [-1, 0, 1, 1, 1, 0, -1, -1] n, m = len(board), len(board[0]) for x inrange(n): for y inrange(m): cnt = 0 for i inrange(8): nx, ny = x + dx[i], y + dy[i] if0 <= nx < n and0 <= ny < m and (board[nx][ny]&1) != 0: cnt += 1 if board[x][y] == 1: board[x][y] += ((1if cnt==2or cnt==3else0) << 1) else: board[x][y] += ((1if cnt==3else0) << 1) for x inrange(n): for y inrange(m): board[x][y] >>= 1