public class Solution {
int m;
int n;
public void gameOfLife(int[][] board) {
m=board.length;
n=board[0].length;
int[][]board2=new int[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
board2[i][j]=board[i][j];
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
int nextState=board2[i][j];
int nibercount=getNiberCount(board2, i, j);
if(nibercount<2)
{
nextState=0;
}
if(nibercount==3)
{
nextState=1;
}
if(nibercount>3)
{
nextState=0;
}
board[i][j]=nextState;
}
}
}
public int getNiberCount(int[][]board2,int x,int y)
{
int startx=Math.max(0, x-1);
int endx=Math.min(m-1, x+1);
int starty=Math.max(0, y-1);
int endy=Math.min(n-1, y+1);
int count=0;
for(int i=startx;i<=endx;i++)
{
for(int j=starty;j<=endy;j++)
{
if(board2[i][j]==1)
{
count++;
}
}
}
return count-=board2[x][y];
}
}
leetcode Game of Life
最新推荐文章于 2019-05-19 10:00:15 发布