1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| public class GameOfLife {
public void solution(int[][] matrix){ if (matrix == null || matrix.length == 0) return ; int index[][] = {{1,-1},{1,1},{-1,-1},{-1,1},{1,0},{-1,0},{0,1},{0,-1}}; for (int i=0; i<matrix.length; i++){ for (int j=0; j<matrix[0].length; j++){ int live = 0; for (int[]ind: index){ if (i+ind[0]<0 || i+ind[0]>=matrix.length || j+ind[1]<0 || j+ind[1]>=matrix[0].length) continue; else if (matrix[i+ind[0]][j+ind[1]] == 1 || matrix[i+ind[0]][j+ind[1]] == 2 ) live ++; } if (matrix[i][j] == 0 && live == 3) matrix[i][j] = 3; if (matrix[i][j] == 1 && (live<2 || live>3)) matrix[i][j] = 2; } } for (int i=0; i<matrix.length; i++){ for (int j=0; j<matrix[0].length; j++) { matrix[i][j] = matrix[i][j] % 2; } } } }
|