1+ /**
2+ * @param {number[][] } board
3+ * @return {void } Do not return anything, modify board in-place instead.
4+ */
5+ var gameOfLife = function ( board ) {
6+ let rows = board . length ;
7+ let cols = board [ 0 ] . length ;
8+ function initMatrix ( rows , cols ) {
9+ let newMatrix = [ ] ;
10+ for ( let i = 0 ; i < rows ; i ++ ) {
11+ newMatrix [ i ] = [ ]
12+ }
13+ return newMatrix ;
14+ }
15+ function getCurrentState ( board , curr_i , curr_j ) {
16+ let start_i = curr_i - 1 > 0 ? curr_i - 1 : 0 ;
17+ let start_j = curr_j - 1 > 0 ? curr_j - 1 :0 ;
18+ let end_i = curr_i + 1 < board . length - 1 ? curr_i + 1 : board . length - 1 ;
19+ let end_j = curr_j + 1 < board [ 0 ] . length - 1 ? curr_j + 1 : board [ 0 ] . length - 1 ;
20+ let neighbors_cnt = 0 ;
21+ for ( let i = start_i ; i <= end_i ; i ++ ) {
22+ for ( let j = start_j ; j <= end_j ; j ++ ) {
23+ if ( board [ i ] [ j ] == 1 ) {
24+ neighbors_cnt ++
25+ }
26+ }
27+ }
28+ let next_element = undefined ;
29+ let current_element = board [ curr_i ] [ curr_j ]
30+ if ( current_element == 1 ) {
31+ //because we can count ourself
32+ neighbors_cnt = neighbors_cnt - 1 ;
33+ next_element = ( neighbors_cnt > 3 || neighbors_cnt < 2 ) ? 0 : 1 ;
34+ } else {
35+ next_element = neighbors_cnt === 3 ? 1 : current_element ;
36+ }
37+ return next_element ;
38+ }
39+
40+ let new_matrix = initMatrix ( rows , cols ) ;
41+ for ( let i = 0 ; i < rows ; i ++ ) {
42+ for ( let j = 0 ; j < cols ; j ++ ) {
43+ new_matrix [ i ] [ j ] = getCurrentState ( board , i , j ) ;
44+ }
45+ }
46+
47+ //copying new_matrix to board
48+ for ( let i = 0 ; i < rows ; i ++ ) {
49+ for ( let j = 0 ; j < cols ; j ++ ) {
50+ board [ i ] [ j ] = new_matrix [ i ] [ j ]
51+ }
52+ }
53+ } ;
0 commit comments