Skip to content

Commit

Permalink
289. Game of Life
Browse files Browse the repository at this point in the history
  • Loading branch information
arpitkekri committed Mar 29, 2021
1 parent 0a4532c commit d7f91b0
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
39 changes: 39 additions & 0 deletions CPP, C++ Solutions/289. Game of Life.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
public:
int numLiveNeighbors(vector<vector<int>>& 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<vector<int>>& 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;
}
}
}
};
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |


<!-- |1808|[Maximize Number of Nice Divisors](https://leetcode.com/problems/maximize-number-of-nice-divisors/)|[C++](./algorithms/cpp/maximizeNumberOfNiceDivisors/MaximizeNumberOfNiceDivisors.cpp)|Hard|Array Math|
|1807|[Evaluate the Bracket Pairs of a String](https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/) | [C++](./algorithms/cpp/evaluateTheBracketPairsOfAString/EvaluateTheBracketPairsOfAString.cpp)|Medium|
Expand Down

0 comments on commit d7f91b0

Please sign in to comment.