leetcode Game of Life

原创 2016年05月31日 10:25:57

题目链接

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

Leetcode Game of Life 相关代码,本题逻辑上相对简单,就是简单的迭代。但是题目要求使用in place完成,这样就得思考一下了,我的实现方案是,先行对数组进行扫描,每个位置对应的数...

Game of Life -- leetcode

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular ...

[LeetCode 289] Game of Life

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular...
  • sbitswc
  • sbitswc
  • 2015年10月12日 07:07
  • 1579

leetcode 289. Game of Life

According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular au...

Leetcode 289. Game of Life (Medium) (cpp)

Leetcode 289. Game of Life (Medium) (cpp)
  • Niko_Ke
  • Niko_Ke
  • 2016年07月31日 23:57
  • 183

Leetcode 289. Game of Life[medium]

题目: According to the Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellul...

【leetcode】289. Game of Life

【leetcode】289. Game of Life

LeetCode刷题【Array】 Game of Life

题目: According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a ...
  • buaalt
  • buaalt
  • 2017年03月20日 10:40
  • 99

LeetCode Game of Life

Description: According to the Wikipedia's article: "The Game of Life, also known simply as Li...

LeetCode:Game of Life

题目描述: According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode Game of Life
举报原因:
原因补充:

(最多只允许输入30个字)