289. Game of Life LeetCode
2016-02-14 19:18
399 查看
题意:生命游戏,给出你这一秒的生物存活情况,和游戏规则。让你给出下一秒生物存活的情况。规则1:如果一个活细胞周围只有1个或者1个以下的活细胞,那么这个细胞下一秒将会死。规则2:如果一个活细胞周围有2个或者3个活细胞,那么这个细胞下一秒将会活着。规则3:如果一个活细胞周围有4个或者4个以上活细胞,那么这个细胞下一秒将会死。规则4:如果一个死细胞周围有3个活细胞,那么这个死细胞下一秒将会活过来。
题解:直接模拟。
题解:直接模拟。
class Solution { public: void gameOfLife(vector<vector<int>>& board) { int dir[8][2] = {{0,1},{0,-1},{1,0},{-1,0},{1,1},{-1,1},{1,-1},{-1,-1}}; int n = board.size(); int m = board[0].size(); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { int count1 = 0; for(int k = 0; k < 8; k++) { int tx = i + dir[k][0]; int ty = j + dir[k][1]; if(tx < 0 || ty < 0 || tx >= n || ty >= m) continue; if(board[tx][ty] == 1 || board[tx][ty] == 3 || board[tx][ty] == 4 || board[tx][ty] == 5) count1++; } if(count1 < 2 && board[i][j] == 1) board[i][j] = 3; else if(count1 >= 2 && count1 <= 3 && board[i][j] == 1) board[i][j] = 4; else if(count1 > 3 && board[i][j] == 1) board[i][j] = 5; if(count1 == 3 && board[i][j] == 0) board[i][j] = 6; } } for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { if(board[i][j] == 3) board[i][j] = 0; else if(board[i][j] == 4) board[i][j] = 1; else if(board[i][j] == 5) board[i][j] = 0; else if(board[i][j] == 6) board[i][j] = 1; } } } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解