LeetCode 289. Game of Life (C++)
阿新 • • 發佈:2018-12-28
題目:
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a board with m by n cells, each cell has an initial state live (1) or dead
- Any live cell with fewer than two live neighbors dies, as if caused by under-population.
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies, as if by over-population..
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
Write a function to compute the next state (after one update) of the board given its current state. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously.
Example:
Input:
[
[0,1,0],
[0,0,1],
[1,1,1],
[0,0,0]
]
Output:
[
[0,0,0],
[1,0,1],
[0,1,1],
[0,1,0]
]
Follow up:
- Could you solve it in-place? Remember that the board needs to be updated at the same time: You cannot update some cells first and then use their updated values to update other cells.
- In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches the border of the array. How would you address these problems?
分析:
矩陣中每個元素為1(live)或0(dead),題目給出了細胞更新的規則,求出更新後的矩陣。規則如下:
- 如果活細胞周圍八個位置的活細胞數少於兩個,則該位置活細胞死亡;
- 如果活細胞周圍八個位置有兩個或三個活細胞,則該位置活細胞仍然存活;
- 如果活細胞周圍八個位置有超過三個活細胞,則該位置活細胞死亡;
- 如果死細胞周圍正好有三個活細胞,則該位置死細胞復活;
首先先判斷元素是0還是1,再計算周圍八個元素的值的和,根據規則更新。建立一個新的二維陣列,最後將計算的值賦給原陣列。
程式:
class Solution { public: void gameOfLife(vector<vector<int>>& board) { vector<vector<int>> res; vector<int> temp; for (int i = 0; i < board.size(); i++){ for (int j = 0; j < board[0].size(); j++){ //dead cell if (board[i][j] == 0){ int alive = 0; for (int m = i-1; m <= i+1; m++){ for (int n = j-1; n <= j+1; n++){ if (m < 0 || m >= board.size() || n < 0 || n >= board[0].size()) continue; else{ if (board[m][n] == 1) alive++; } } } if (alive == 3) temp.push_back(1); else temp.push_back(0); } //live cell else{ int al = 0; for (int m = i-1; m <= i+1; m++){ for (int n = j-1; n <= j+1; n++){ if (m < 0 || m >= board.size() || n < 0 || n >= board[0].size()) continue; else{ if (board[m][n] == 1) al++; } } } //計算了board[m][n]的值,所以判斷條件+1 if (al < 3) temp.push_back(0); else if (al > 4) temp.push_back(0); else temp.push_back(1); } } res.push_back(temp); temp.clear(); } for (int i = 0; i < board.size(); i++){ for (int j = 0; j < board[0].size(); j++){ board[i][j] = res[i][j]; } } } };
備註:
做法是新開闢了一個數組,以後再更新下用原陣列的程式。