game-of-life.dart (2487B)
1 //Given the rules of Conway's game of life create a function 2 //that simulates one iteration of it. 3 //I simply iterated through each square of the original matrix 4 //and checked the neighbors it has then based on that in the original matrix 5 //it was updated. 6 //Time: 243ms Beats: 100% 7 //Memory: 141MB Beats: 100% 8 class Solution { 9 void gameOfLife(List<List<int>> board) { 10 List<List<int>> temp = []; 11 for(int i = 0 ; i < board.length ; ++i){ 12 temp.add(List.from(board[i])); 13 } 14 for(int i = 0 ; i < temp.length ; ++i){ 15 for(int x = 0 ; x < temp[i].length ; ++x){ 16 bool alive = (temp[i][x] == 1); 17 int neighbors = 0; 18 // Top 19 if(i != 0){ 20 if(temp[i - 1][x] == 1){ 21 neighbors += 1; 22 } 23 } 24 // Left 25 if(x != 0){ 26 if(temp[i][x - 1] == 1){ 27 neighbors += 1; 28 } 29 } 30 // Right 31 if(x != temp[i].length - 1){ 32 if(temp[i][x + 1] == 1){ 33 neighbors += 1; 34 } 35 } 36 // Bottom 37 if(i != temp.length - 1){ 38 if(temp[i + 1][x] == 1){ 39 neighbors += 1; 40 } 41 } 42 // Top Left 43 if(i != 0 && x != 0){ 44 if(temp[i - 1][x - 1] == 1){ 45 neighbors += 1; 46 } 47 } 48 // Top Right 49 if(i != 0 && x != temp[i].length - 1){ 50 if(temp[i - 1][x + 1] == 1){ 51 neighbors += 1; 52 } 53 } 54 // Bottom Left 55 if(i != temp.length - 1 && x != 0){ 56 if(temp[i + 1][x - 1] == 1){ 57 neighbors += 1; 58 } 59 } 60 // Bottom Right 61 if(i != temp.length - 1 && x != temp[i].length - 1){ 62 if(temp[i + 1][x + 1] == 1){ 63 neighbors += 1; 64 } 65 } 66 if(alive){ 67 if(neighbors < 2 || neighbors > 3){ 68 board[i][x] = 0; 69 } 70 } 71 else{ 72 if(neighbors == 3){ 73 board[i][x] = 1; 74 } 75 } 76 } 77 } 78 } 79 }