|
| 1 | +packagemedium; |
| 2 | + |
| 3 | +publicclassGameOfLife { |
| 4 | +publicvoidgameOfLife(int[][]board) { |
| 5 | +intheight =board.length,width =board[0].length; |
| 6 | +int[][]next =newint[height][width]; |
| 7 | + |
| 8 | +for(inti =0;i <board.length;i++){ |
| 9 | +for(intj =0;j <board[0].length;j++){ |
| 10 | +intliveCellsCount =0; |
| 11 | +//count all its live cells |
| 12 | + |
| 13 | +if(j+1 <width &&board[i][j+1] ==1)liveCellsCount++;//right cell |
| 14 | +if(j-1 >=0 &&board[i][j-1] ==1)liveCellsCount++;//left cell |
| 15 | +if(i+1 <height &&board[i+1][j] ==1)liveCellsCount++;//down cell |
| 16 | +if(i-1 >=0 &&board[i-1][j] ==1)liveCellsCount++;//up cell |
| 17 | +if(i-1 >=0 &&j-1 >=0 &&board[i-1][j-1] ==1)liveCellsCount++;//up left cell |
| 18 | +if(i-1 >=0 &&j+1 <width &&board[i-1][j+1] ==1)liveCellsCount++;//up right cell |
| 19 | +if(i+1 <height &&j-1 >=0 &&board[i+1][j-1] ==1)liveCellsCount++;//down left cell |
| 20 | +if(i+1 <height &&j+1 <width &&board[i+1][j+1] ==1)liveCellsCount++;//down right cell |
| 21 | + |
| 22 | +if(board[i][j] ==1){ |
| 23 | +if(liveCellsCount >3 ||liveCellsCount <2) { |
| 24 | +next[i][j] =0; |
| 25 | + }else { |
| 26 | +next[i][j] =1; |
| 27 | + } |
| 28 | + }elseif(board[i][j] ==0) { |
| 29 | +if(liveCellsCount ==3){ |
| 30 | +next[i][j] =1; |
| 31 | + } |
| 32 | + } |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | +for(inti =0;i <board.length;i++){ |
| 37 | +for(intj =0;j <board[0].length;j++){ |
| 38 | +board[i][j] =next[i][j]; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | +} |