Skip to content

Commit 71fdf96

Browse files
authored
Merge pull request #1511 from ivan1016017/january09
adding algo
2 parents 04e6774 + d45485a commit 71fdf96

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
class Solution:
5+
def gameOfLife(self, board: List[List[int]]) -> None:
6+
7+
"""
8+
Do not return anything, modify board in-place instead.
9+
"""
10+
## RC ##
11+
## APPRAOCH : IN-PLACE MANIPULATION ##
12+
# when the value needs to be updated, we donot just change
13+
# 0 to 1 / 1 to 0 but we do in increments and decrements of 2.
14+
# (table explains)
15+
## previous value state change current state current value
16+
## 0 no change dead 0
17+
## 1 no change live 1
18+
## 0 changed (+2) live 2
19+
## 1 changed (-2) dead -1
20+
21+
## TIME COMPLEXITY : O(MxN) ##
22+
## SPACE COMPLEXITY : O(1) ##
23+
24+
directions = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]
25+
26+
for i in range(len(board)):
27+
for j in range(len(board[0])):
28+
live = 0
29+
for x, y in directions:
30+
if ( 0<= i + x < len(board)) \
31+
and (0<= j + y < len(board[0])) \
32+
and abs(board[i+x][j+y]) == 1:
33+
live += 1
34+
35+
if board[i][j] == 1 and (live < 2 or live > 3):
36+
board[i][j] = -1
37+
if board[i][j] == 0 and live == 3:
38+
board[i][j] = 2
39+
40+
for i in range(len(board)):
41+
for j in range(len(board[0])):
42+
board[i][j] = 1 if(board[i][j] > 0) else 0
43+
return board
44+
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_22\
3+
.ex_37_game_of_life import Solution
4+
5+
class GameOfLifeTestCase(unittest.TestCase):
6+
7+
def test_first_pattern(self):
8+
solution = Solution()
9+
output = solution.gameOfLife(board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]])
10+
target = [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
11+
self.assertEqual(output, target)
12+
13+
def test_second_pattern(self):
14+
solution = Solution()
15+
output = solution.gameOfLife(board = [[1,1],[1,0]])
16+
target = [[1,1],[1,1]]
17+
self.assertEqual(output, target)

0 commit comments

Comments
 (0)