Skip to content

Latest commit

 

History

History
58 lines (57 loc) · 1.56 KB

File metadata and controls

58 lines (57 loc) · 1.56 KB
  • 周围活细胞数为 2 时当前细胞状态不变,为 3 时当前细胞存活,其它情况当前细胞死亡。计算周围活细胞数,修改状态即可。为了防止修改状态影响之后的结果,先临时修改为一个可判断的同类状态
class Solution {
 public:
  void gameOfLife(vector<vector<int>>& board) {
    if (empty(board) || empty(board[0])) {
      return;
    }
    int m = size(board);
    int n = size(board[0]);
    for (int i = 0; i < m; ++i) {
      for (int j = 0; j < n; ++j) {
        int cnt = 0;
        if (i > 0 && j > 0 && board[i - 1][j - 1] > 0) {
          ++cnt;
        }
        if (i > 0 && board[i - 1][j] > 0) {
          ++cnt;
        }
        if (i > 0 && j + 1 < n && board[i - 1][j + 1] > 0) {
          ++cnt;
        }
        if (j > 0 && board[i][j - 1] > 0) {
          ++cnt;
        }
        if (j + 1 < n && board[i][j + 1] > 0) {
          ++cnt;
        }
        if (i + 1 < m && j > 0 && board[i + 1][j - 1] > 0) {
          ++cnt;
        }
        if (i + 1 < m && board[i + 1][j] > 0) {
          ++cnt;
        }
        if (i < m - 1 && j + 1 < n && board[i + 1][j + 1] > 0) {
          ++cnt;
        }
        if (cnt == 3 && !board[i][j]) {
          board[i][j] = -1;  // 最终为 1
        }
        if (cnt != 2 && cnt != 3 && board[i][j] == 1) {
          board[i][j] = 2;  // 最终为 0
        }
      }
    }
    for (auto& x : board) {
      for (auto& y : x) {
        if (y == -1) {
          y = 1;
        } else if (y == 2) {
          y = 0;
        }
      }
    }
  }
};