From d7f91b02414c3d4b95cae46a7c26f773079ab2bd Mon Sep 17 00:00:00 2001 From: arpitkekri Date: Mon, 29 Mar 2021 21:41:26 +0530 Subject: [PATCH] 289. Game of Life --- CPP, C++ Solutions/289. Game of Life.cpp | 39 ++++++++++++++++++++++++ README.md | 2 +- 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 CPP, C++ Solutions/289. Game of Life.cpp diff --git a/CPP, C++ Solutions/289. Game of Life.cpp b/CPP, C++ Solutions/289. Game of Life.cpp new file mode 100644 index 0000000..f1fac7d --- /dev/null +++ b/CPP, C++ Solutions/289. Game of Life.cpp @@ -0,0 +1,39 @@ +class Solution { +public: + int numLiveNeighbors(vector>& board, int i, int j) { + int n = board.size(); + int m = board[0].size(); + int ans = 0; + for(int s = i-1; s <= i+1; s++) { + for(int e = j-1; e <= j+1; e++) { + if(s == i && e == j) continue; + if((s >= 0 && s < n) && (e >= 0 && e < m) && (board[s][e] >= 1)) ans++; + } + } + return ans; + } + void gameOfLife(vector>& board) { + int n = board.size(); + int m = board[0].size(); + int neighbour; + for(int i = 0; i < n; i++) { + for(int j = 0; j < m; j++) { + if(board[i][j] == 1) { + neighbour = numLiveNeighbors(board, i, j); + if(neighbour == 2 || neighbour == 3) board[i][j]++; + } + else { + neighbour = numLiveNeighbors(board, i, j); + if(neighbour == 3) board[i][j]--; + } + } + } + for(int i = 0; i < n; i++) { + for(int j = 0; j < m; j++) { + if(board[i][j] == -1 || board[i][j] == 2) + board[i][j] = 1; + else board[i][j] *= 0; + } + } + } +}; \ No newline at end of file diff --git a/README.md b/README.md index 3fe92a5..68f9978 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ | # | Title | Solution | Time | Space | Difficulty | Tag | |---| ----- | -------- | ---- | ----- | ---------- | --- | |1|[Two Sum](https://leetcode.com/problems/two-sum/)| [C++](./CPP%2C%20C%2B%2B%20Solutions/1.%20Two%20Sum_1.cpp) | _O(n^2)_ | _O(n)_ | Easy | Array, Hash Table | -|1|[Two Sum](https://leetcode.com/problems/two-sum/)| [C++](./CPP%2C%20C%2B%2B%20Solutions/1.%20Two%20Sum_1.cpp) | _O(n^2)_ | _O(n)_ | Easy | Array, Hash Table | +