diff --git a/src/my_project/interviews/top_150_questions_round_22/ex_37_game_of_life.py b/src/my_project/interviews/top_150_questions_round_22/ex_37_game_of_life.py new file mode 100644 index 00000000..e16090c1 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_22/ex_37_game_of_life.py @@ -0,0 +1,44 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +class Solution: + def gameOfLife(self, board: List[List[int]]) -> None: + + """ + Do not return anything, modify board in-place instead. + """ + ## RC ## + ## APPRAOCH : IN-PLACE MANIPULATION ## + # when the value needs to be updated, we donot just change + # 0 to 1 / 1 to 0 but we do in increments and decrements of 2. + # (table explains) + ## previous value state change current state current value + ## 0 no change dead 0 + ## 1 no change live 1 + ## 0 changed (+2) live 2 + ## 1 changed (-2) dead -1 + + ## TIME COMPLEXITY : O(MxN) ## + ## SPACE COMPLEXITY : O(1) ## + + directions = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)] + + for i in range(len(board)): + for j in range(len(board[0])): + live = 0 + for x, y in directions: + if ( 0<= i + x < len(board)) \ + and (0<= j + y < len(board[0])) \ + and abs(board[i+x][j+y]) == 1: + live += 1 + + if board[i][j] == 1 and (live < 2 or live > 3): + board[i][j] = -1 + if board[i][j] == 0 and live == 3: + board[i][j] = 2 + + for i in range(len(board)): + for j in range(len(board[0])): + board[i][j] = 1 if(board[i][j] > 0) else 0 + return board + diff --git a/tests/test_150_questions_round_22/test_37_game_of_life_round_22.py b/tests/test_150_questions_round_22/test_37_game_of_life_round_22.py new file mode 100644 index 00000000..4a2f298d --- /dev/null +++ b/tests/test_150_questions_round_22/test_37_game_of_life_round_22.py @@ -0,0 +1,17 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_22\ +.ex_37_game_of_life import Solution + +class GameOfLifeTestCase(unittest.TestCase): + + def test_first_pattern(self): + solution = Solution() + output = solution.gameOfLife(board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]) + target = [[0,0,0],[1,0,1],[0,1,1],[0,1,0]] + self.assertEqual(output, target) + + def test_second_pattern(self): + solution = Solution() + output = solution.gameOfLife(board = [[1,1],[1,0]]) + target = [[1,1],[1,1]] + self.assertEqual(output, target)