LeetCode – Game of Life Problem | Solution with JavaScript

### Problem Statement –

According to Wikipedia’s article: “The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970.”

The board is made up of a `m x n` grid of cells, where each cell has an initial state: live (represented by a `1`) or dead (represented by a `0`). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):

1. Any live cell with fewer than two live neighbors dies as if caused by under-population.
2. Any live cell with two or three live neighbors lives on to the next generation.
3. Any live cell with more than three live neighbors dies, as if by over-population.
4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid, return the next state.

Example 1:

``````Input: board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
Output: [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]``````

Example 2:

``````Input: board = [[1,1],[1,0]]
Output: [[1,1],[1,1]]``````

### 💡 Logic of Dead and Alive

After a clear understanding of the above problem, we have to keep two main conditions in mind for Live and Dead based on their neighbors.

1. Live Element (1) will die (0) if their neighbors are less than two ( < 2) or more than three ( > 3) alive.
2. The dead (0) element will be live (1) if there are exactly three neighbors (== 3) alive.
```if (element === live) {
if (liveNeighbors < 2 || liveNeighbors > 3) {
}
}
else if (liveNeighbors === 3) {
element = live;
}
```

### 💡 Logic of Finding Neighbors of an element

There is a total of 8 neighbors of an element in a 2-dimensional array. Top, Left, Bottom, and Right elements, and Four are Diagonal elements.

``` [-1, 0], // up
[0, 1],  // right
[1, 0], // down
[0, -1] // left
[-1, -1], [-1, 1], [1, 1], [1, -1] // Diagonal Directions.
```

Traversing 2 D array with BFS & DFS Algorithm in JavaScript

Code </>

💻 SOLUTION USING DFS

```/**
* @param {number[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var gameOfLife = function (board) {
// if board is empty
if (!board.length) {
return;
}
const directions = [
[-1, 0], // up
[0, 1],  // right
[1, 0], // down
[0, -1] // left
];
const sideDirections = [[-1, -1], [-1, 1], [1, 1], [1, -1]];
const allNeighbors = directions.concat(sideDirections);

// we will update true for visited element so that we could trace which item has been visited
let seen = new Array(board.length).fill('').map(() => new Array(board[0].length).fill(false));

// cloned original board to get real values because we will update live and dead in real board
let clonedBoard = JSON.parse(JSON.stringify(board));
// console.log('clonedBoard :', clonedBoard);

dfs(board, 0, 0, clonedBoard, seen, directions, allNeighbors);
//console.log('board :', board);

};

function dfs(board, row, col, clonedBoard, seen, directions, allNeighbors) {

if (row < 0 || row >= board.length ||
col < 0 || col >= board[0].length ||
seen[row][col]) {
return;
}

/* RULES OF DEAD & LIVE
1 -> 0 (when live neighbors are  < 2  or > 3) means 1 will be 1 for only 2 or 3 neighbors.
0  -> 1 (when live neighbors are 3 ) */
let countLive = 0;
for (let i = 0; i < allNeighbors.length; i++) {
const neighbor = allNeighbors[i];
const rowPosition = row + neighbor[0];
const colPosition = col + neighbor[1];
if (rowPosition >= 0 && rowPosition < board.length &&
colPosition >= 0 && colPosition < board[0].length) {
if (clonedBoard[rowPosition][colPosition] === 1) {
countLive++;
}
}
}
const ele = board[row][col];
seen[row][col] = true; // update true into seen once element visited
if (ele === 1) { // live
if (countLive < 2 || countLive > 3) {
board[row][col] = 0;
}
if (countLive === 3) {
board[row][col] = 1;
}
}

// travering all elements of 2 d array
for (let i = 0; i < directions.length; i++) {
let direction = directions[i];
dfs(board, row + direction[0], col + direction[1], clonedBoard, seen, directions, allNeighbors);
}
}```

💻 SOLUTION USING 2 NESTED FOR LOOP

```/**
* @param {number[][]} board
* @return {void} Do not return anything, modify board in-place instead.
*/
var gameOfLife1 = function (board) {
// if board is empty
if (!board.length) {
return;
}
const directions = [
[-1, 0], // up
[0, 1],  // right
[1, 0], // down
[0, -1] // left
];
const sideDirections = [[-1, -1], [-1, 1], [1, 1], [1, -1]];
const allNeighbors = directions.concat(sideDirections);

// cloned original board to get real values because we will update live and dead in real board
let clonedBoard = JSON.parse(JSON.stringify(board));
// console.log('clonedBoard :', clonedBoard);

for (let i = 0; i < board.length; i++) {
let row = board[i];
for (let j = 0; j < row.length; j++) {

}
}
// console.log('board :', board);

};

function updateLiveAndDead(board, row, col, clonedBoard, allNeighbors) {

/* RULES OF DEAD & LIVE
1 -> 0 (when live neighbors are  < 2  or > 3) means 1 will be 1 for only 2 or 3 neighbors.
0  -> 1 (when live neighbors are 3 ) */
let countLive = 0;
for (let i = 0; i < allNeighbors.length; i++) {
const neighbor = allNeighbors[i];
const rowPosition = row + neighbor[0];
const colPosition = col + neighbor[1];
if (rowPosition >= 0 && rowPosition < board.length &&
colPosition >= 0 && colPosition < board[0].length) {
if (clonedBoard[rowPosition][colPosition] === 1) {
countLive++;
}
}
}
const ele = board[row][col];
if (ele === 1) { // live
if (countLive < 2 || countLive > 3) {
board[row][col] = 0;
}
if (countLive === 3) {
board[row][col] = 1;
}
}
}```

Output –

```gameOfLife([[0, 1, 0], [0, 0, 1], [1, 1, 1], [0, 0, 0]])

> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
```

HackerRank Dictionaries and Maps Problem | Solution with JavaScript

Trapping Rain Water Leetcode Problem Solution

Backspace String Compare Leetcode Problem & Solution

Fibonacci series in JavaScript | Four different ways

Array Representation of Binary Tree | Full Tree & Complete Binary Tree

Graphs in Data Structure, Types & Traversal with BFS and DFS, Algorithms

Traversing 2 D array with BFS & DFS Algorithm in JavaScript

JavaScript Rotate 2D matrix 90 degrees clockwise | Top Interview Question

HashTable Data Structure in JavaScript with Add Delete & Search Algorithms

LeetCode – Game of Life Problem | Solution with JavaScript