其他分享
首页 > 其他分享> > leetcode 289. Game of Life

leetcode 289. Game of Life

作者:互联网

class GameOfLife {
    public static void gameOfLife(int[][] board) {
        int[][] copy = new int[board.length][board[0].length];

        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[i].length; j++){
                copy[i][j] = board[i][j];
            }
        }

        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[i].length; j++){
                copy[i][j] = board[i][j];
                if( board[i][j] == 1){
                   if(checkCells(board, i, j) == 2 || checkCells(board, i, j) == 3){
                    copy[i][j] = 1;
                }else{
                    copy[i][j] = 0;
                } 
                }else if(board[i][j] == 0){
                   if(checkCells(board, i, j) == 3){
                    copy[i][j] = 1;
                }else{
                    copy[i][j] = 0;
                }  
                }
            }
        }

        for(int i = 0; i < board.length; i++){
            for(int j = 0; j < board[i].length; j++){
                board[i][j] = copy[i][j];
            }
        }
    }


    private static int checkCells(int[][] board, int row, int col){
        int con = 0;
        int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0},{1,-1},{-1,1},{1,1},{-1,-1}};
        for(int[] dir:dirs){
            int x = row + dir[0];
            int y = col + dir[1];
            if( !(x < 0 || x >= board.length || y < 0 || y >= board[0].length)){
              if(board[x][y] == 1){
                    con++;
                }
            }
        }
        return con;
        
    }

}

 

标签:int,length,checkCells,289,++,Game,board,copy,leetcode
来源: https://www.cnblogs.com/queg/p/16146155.html