A simple anwser to extend the m*n board to (m+2)*(n+2)


  • -1
    R
       void gameOfLife(vector< vector<int> >& board) {
            int m=board.size(),n=board[0].size();
            if(m==0 || n==0)
                return;
            vector< vector<int> > temp(m,vector<int>(n));
            //对原board进行扩展,增加最外圈,假设做外圈所有细胞都是死亡的,状态为0 
            for(int i=0;i<m;i++){
            	board[i].push_back(0);
            	board[i].insert(board[i].begin(),0);
        	}
        	board.push_back(vector<int>(n+2));
        	board.insert(board.begin(),vector<int>(n+2));
        
        	for(int j=1;j<m+1;j++) {
        		for(int k=1;k<n+1;k++) {
        			int count = live(j,k,board);
        			if(board[j][k]==1){
        				if(count<2)
        					temp[j-1][k-1]=0;
        				if(count==2 || count==3)
        					temp[j-1][k-1]=1;
        				if(count>3)
        					temp[j-1][k-1]=0;
        			}
        			else if(board[j][k]==0){
        				if(count==3)
        					temp[j-1][k-1]=1;
        			}
        		}
        	} 
        	board = temp;
        }
        
        int live(int x,int y,vector< vector<int> >& matrix) {
        	int count=0;
        	for(int i=x-1;i<=x+1;i++){
        		for(int j=y-1;j<=y+1;j++)
        			if(matrix[i][j])
        				count++;
        	}
        	return count-matrix[x][y];
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.