289. 生命游戏
1 class Solution 2 { 3 int dx[8] = {1,1,0,-1,-1,-1,0,1}; 4 int dy[8] = {0,1,1,1,0,-1,-1,-1}; 5 public: 6 void gameOfLife(vector<vector<int>>& board) 7 { 8 int m = board.size(),n = board[0].size(); 9 vector<vector<bool>> visit(m,vector<bool>(n,false)); 10 for(int i = 0;i < m;i ++) 11 { 12 for(int j = 0;j < n;j ++) 13 { 14 if(board[i][j]) visit[i][j] = true; 15 } 16 } 17 18 for(int i = 0;i < m;i ++) 19 { 20 for(int j = 0;j < n;j ++) 21 { 22 if(visit[i][j]) 23 { 24 int count = 0; 25 for(int k = 0;k < 8;k ++) 26 { 27 int x = i + dx[k]; 28 int y = j + dy[k]; 29 if(x >= 0 && x < m && y >= 0 && y < n && visit[x][y]) count++; 30 } 31 if(count < 2 || count > 3) board[i][j] = 0; 32 } 33 else 34 { 35 int count = 0; 36 for(int k = 0;k < 8;k ++) 37 { 38 int x = i + dx[k]; 39 int y = j + dy[k]; 40 if(x >= 0 && x < m && y >= 0 && y < n && visit[x][y]) count++; 41 } 42 if(count == 3) board[i][j] = 1; 43 } 44 } 45 } 46 } 47 };
Mamba never out

浙公网安备 33010602011771号