leetcode 289. Game of Life
阿新 • • 發佈:2022-04-14
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; } }