本文主要是介绍289. 生命游戏——数组,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
class Solution {
public:void gameOfLife(vector<vector<int>>& board) {int rows = board.size(), columns = board[0].size();for(int row = 0; row < rows; ++row){for(int column = 0; column < columns; ++column){int live = 0;//检查周围8个for(int i = -1; i <= 1; ++i){for(int j = -1; j <= 1; ++j){//跳过自己if(i == 0 && j == 0)continue;int r = row + i;int c = column + j;//前面防止越界,后面判定该细胞存活则++if(r >=0 && r < rows && c >= 0 && c < columns && board[r][c] >= 1)++live;}}//曾经是活的,结果死了if(board[row][column] == 1 && (live <2 || live > 3))board[row][column] = 2;//回光返照状态//曾经是死的,结果活了if(board[row][column] == 0 && live == 3)board[row][column] = -1;//假死状态}}//然后让死的死,活的活for(int row = 0; row < rows; ++row){for(int column = 0; column < columns; ++column){if(board[row][column] == 0 || board[row][column] == 1)continue;if(board[row][column] == 2)board[row][column] = 0;else if(board[row][column] == -1)board[row][column] = 1;}}}
};
Accepted
22/22 cases passed (0 ms)
Your runtime beats 100 % of cpp submissions
Your memory usage beats 54.78 % of cpp submissions (6.7 MB)
这篇关于289. 生命游戏——数组的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!