↓ Skip to main content
  1. Posts/

leetcode 289. Game of Life (模拟)

·1065 words·3 mins
Note: This article is available in Chinese only. 本文暂无英文版本。 View original

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 (0). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

  1. Any live cell with fewer than two live neighbors dies, as if caused by under-population.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by over-population..
  4. 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.

Follow up:

  1. 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.
  2. 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?

题意:生命游戏。。。看到follow up本以为是提高篇,结果不是题目要求。可是第一个又说 board要同时更新,这是要求吧。于是我就按照棋盘是二维环来写的,最后发现棋盘是有限的。

也就是两个follow up,要看1(同时变换),不要看2(实际上棋盘是有限的)。这不是有毒吗?

所以做leetcode最大的挑战是如何保持心平气和,不要被傻逼题目以及傻逼题目描述影响心情(

我直接写了棋盘是二维环的版本。注意的就是,八个方向遍历后记得去重,以及不能和起点相同。

同时更新再加两个标记就好了。

1代表活的,0代表死了

-1代表刚才活的,现在死了

-2代表刚才死的,现在活了。

最后记得再变回来。。。

代码实现
  1/* ***********************************************
  2Author :111qqz
  3Created Time :2017年04月05日 星期三 18时52分29秒
  4File Name :289.cpp
  5************************************************ */
  6class Solution {
  7
  8public:
  9    const int dx[8]={1,1,1,0,0,-1,-1,-1};
 10    const int dy[8]={-1,0,1,-1,1,-1,0,1};
 11    const int N=1E3+3;
 12    int n,m;
 13    int checkX( int x)
 14    {
 15	if (x>=0&&x<=n-1) return x;
 16	if (x==n) return 0;
 17	if (x==-1) return n-1;
 18    }
 19    int checkY( int y)
 20    {
 21	if (y>=0&&y<=m-1) return y;
 22	if (y==m) return 0;
 23	if (y==-1) return m-1;
 24    }
 25    bool check ( int x,int y) //follow up 里的不是题意啊。。。有毒。。。
 26    {
 27	if (x>=0&&x<=n-1&&y>=0&&y<=m-1) return true;
 28	return false;
 29    }
 30
 31    int live( int x,int y,vector<vector<int> >& maze)
 32    {
 33	int cnt = 0 ;
 34	set < pair < int ,int > > se;
 35
 36	for ( int i = 0 ; i < 8 ;  i++) //八个方向经过check以后可能有相同的orz...
 37	{				//还可能遇到自己orz...
 38	    int nx = x + dx[i];
 39	    int ny = y + dy[i];
 40	   // nx = checkX(nx);
 41	   // ny = checkY(ny);
 42	    if (!check(nx,ny)) continue;
 43	    if (nx==x&&ny==y) continue;
 44//	    cout<<"nx:"<<nx<<" ny:"<<ny<<" maze:"<<maze[nx][ny]<<endl;
 45	    if (maze[nx][ny]==1||maze[nx][ny]==-1) se.insert(make_pair(nx,ny));
 46	}
 47	cnt = se.size();
 48	//cout<<"x:"<<x<<" y:"<<y<<" cnt:"<<cnt<<endl;
 49	if (cnt<2||cnt>3) return -1;
 50	else
 51	return 1;
 52
 53    }						    //1 -> live ,0->dead
 54    int dead( int x,int y,vector<vector<int> >& maze) //-1>刚才活的,现在死了, -2->刚才死的,现在活了
 55    {
 56	int cnt = 0 ;
 57	set< pair <int,int > >se;
 58	for ( int i = 0 ; i < 8  ; i++)
 59	{
 60	    int nx = x + dx[i];
 61	    int ny = y + dy[i];
 62	    //nx = checkX(nx);
 63	    //ny = checkY(ny);
 64	    if (!check(nx,ny)) continue;
 65	    if (nx==x&&ny==y) continue;
 66//	    printf("nx:%d ny:%d\n",nx,ny);
 67	    if (maze[nx][ny]==1||maze[nx][ny]==-1) se.insert(make_pair(nx,ny));
 68	}
 69	cnt = se.size();
 70	if (cnt==3) return -2; //死的变活了
 71	return 0;
 72
 73    }
 74    void gameOfLife(vector<vector<int>>& board) {
 75	n = board.size();
 76	if (n==0) return;
 77	m = board[0].size();
 78	if (m==0) return;
 79	for ( int i  = 0 ; i < n ; i++)
 80	{
 81	    for ( int j = 0 ;j < m ; j++)
 82	    {
 83		int tmp = board[i][j];
 84//		cout<<"val:"<<tmp<<endl;
 85		if (tmp==1||tmp==-1)
 86		{
 87		    board[i][j] = live(i,j,board);
 88		}
 89		else if (tmp==0||tmp==-2)
 90		     {
 91			 board[i][j] = dead(i,j,board);
 92		     }
 93	    }
 94	 }
 95	for ( int i = 0 ;i < n ; i++)
 96	    for ( int j = 0 ; j < m ; j++)
 97		if (board[i][j]==-2) board[i][j] = 1;
 98		else if (board[i][j]==-1) board[i][j] = 0;
 99
100    }
101
102};

Related

leetcode 90. Subsets II (枚举子集)

·266 words·1 min
Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: The solution set must not contain duplicate subsets. For example, If nums = [1,2,2], a solution is: 1[ 2 [2], 3 [1], 4 [1,2,2], 5 [2,2], 6 [1,2], 7 [] 8] 思路: 复习(?)一下 枚举子集的三种写法 (还有种更飘逸的…先不写了orz 这道题我用位向量法A的。。

106. Construct Binary Tree from Inorder and Postorder Traversal(根据中序和后序遍历构建二叉树)

·206 words·1 min
1/* *********************************************** 2Author :111qqz 3Created Time :2017年04月05日 星期三 16时49分57秒 4File Name :106.cpp 5************************************************ */ 6/** 7 * Definition for a binary tree node. 8 * struct TreeNode { 9 * int val; 10 * TreeNode *left; 11 * TreeNode *right; 12 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 13 * }; 14 */ 15class Solution { 16public: 17 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { 18 int siz = inorder.size(); 19 if (siz==0) return NULL; 20 int rt = postorder[siz-1]; 21 int pos = -1; 22 for ( int i = 0 ; i < siz; i++) 23 { 24 if (inorder[i]==rt) 25 { 26 pos = i ; 27 break; 28 } 29 } 30 TreeNode *head = new TreeNode(rt); 31 vector<int>in,post; 32 for ( int i = 0 ; i < pos ; i++) 33 { 34 in.push_back(inorder[i]); 35 post.push_back(postorder[i]); 36 } 37 head->left = buildTree(in,post); 38 in.clear(); 39 post.clear(); 40 for ( int i = pos + 1 ; i < siz ; i++) 41 { 42 in.push_back(inorder[i]); 43 post.push_back(postorder[i-1]); 44 } 45 head->right = buildTree(in,post); 46 return head; 47 } 48};

leetcode 287. Find the Duplicate Number (floyd判圈算法找重复元素)

·422 words·1 min
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one. Note: 1. You **must not** modify the array (assume the array is read only). 2. You must use only constant, _O_(1) extra space. 3. Your runtime complexity should be less than `O(n2)`. 4. There is only one duplicate number in the array, but it could be repeated more than once. 思路:O(n^2)的复杂度暴力即可,说个O(n)复杂度的解法。

leetcode 532. K-diff Pairs in an Array (找差为k的数对)

·557 words·2 mins
Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. Example 1: 1Input: [3, 1, 4, 1, 5], k = 2 2Output: 2 3Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5). 4Although we have two 1s in the input, we should only return the number of unique pairs. Example 2:

leetcode 448. Find All Numbers Disappeared in an Array(寻找所有消失的元素)

·341 words·1 min
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. Example: Input: [4,3,2,7,8,2,3,1] Output: [5,6] 思路:由于元素大小有限制,是在1..n之间。