力扣 289. 生命游戏

虽然难度是中等但其实很简单
遍历矩阵判断每个点是死是活就可以了
进阶要求使用原地算法,即空间复杂度为O(1) ,所以我们不能简单的记录1是活,0是死,
我规定 1 原来活 活变活
0 原来死 死变死
2 死变活
-1 活变死

自己的(0ms)

class Solution {
    public void gameOfLife(int[][] board) {
        //1 原来活   活变活
        //0 原来死   死变死
        //2 死变活
        //-1 活变死
        for(int i = 0; i < board.length; i++)
            for(int j = 0; j < board[0].length; j++){
                int n = 0;
                if(i - 1 >= 0){
                    if(board[i - 1][j] == 1 || board[i - 1][j] == -1)
                        n ++;
                    if(j - 1 >= 0)
                        if(board[i - 1][j - 1] == 1 || board[i - 1][j - 1] == -1)
                            n ++;
                    if(j + 1 < board[0].length)
                        if(board[i - 1][j + 1] == 1 || board[i - 1][j + 1] == -1)
                            n ++;
                }
                if(i + 1 < board.length){
                    if(board[i + 1][j] == 1 || board[i + 1][j] == -1)
                        n ++;
                    if(j - 1 >= 0)
                        if(board[i + 1][j - 1] == 1 || board[i + 1][j - 1] == -1)
                            n ++;
                    if(j + 1 < board[0].length)
                        if(board[i + 1][j + 1] == 1 || board[i + 1][j + 1] == -1)
                            n ++;
                }
                if(j - 1 >= 0)
                    if(board[i][j - 1] == 1 || board[i][j - 1] == -1)
                        n ++;
                if(j + 1 < board[0].length)
                    if(board[i][j + 1] == 1 || board[i][j + 1] == -1)
                        n ++;
                if(n < 2 || n >3)
                    if(board[i][j] == 1)
                        board[i][j] = -1;
                if(n == 3)
                    if(board[i][j] == 0)
                        board[i][j] = 2;
            }
        for(int i = 0; i < board.length; i++)
            for(int j = 0; j < board[0].length; j++){
                if(board[i][j] == 2)
                    board[i][j] = 1;
                if(board[i][j] == -1)
                    board[i][j] = 0;
            }
    }
}

你可能感兴趣的:(leetcode,游戏,算法)