Problem of the day
You’re given a board of N * M size. Each element of this board is represented by either 0 or 1, where 0 means ‘dead’ and 1 means ‘live’. Each element can interact with all of its eight neighbors using the following four rules.
If any live cell has less than two live neighbors, then it dies.
If any live cell has two or three live neighbors, then it lives onto the next generation.
If any live cell has more than three live neighbors, then it dies.
A dead element with exactly three live neighbors becomes a live element.
Your task is to print the next state of this board using these four rules.
The first line of the input contains an integer T denoting the number of test cases.
The first line of every test case contains two space-separated integers N and M, denoting the number of rows and columns, respectively.
The next N lines of each test case contain M space-separated integers denoting the elements of the board.
Output Format :
For every test case, print the next state of the board using the four rules described in the problem statement.
Note :
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= M, N <= 1000
Time limit: 1 sec
1
2 2
1 0
0 1
0 0
0 0
The first element(0,0) and the fourth element(1,1) are ‘live’ and have one live and two dead neighbors. Hence they both will die and become 0 in the next state. The second element(0,1) and the third element(1,0) are ‘dead’ and have one dead and two live neighbors. Hence they will also die and become 0 in the next state.
1
3 3
0 0 1
0 0 0
1 0 1
0 0 0
0 1 0
0 0 0
Keep a count of the live elements.
1. Start by creating two arrays, “xDirections” and “yDirections,” containing all the neighbors’ possible directions.
“xDirections” = {0, 0, 1, 1 ,1, -1, -1, -1}
“yDirections” = {1, -1, 1, -1, 0, 0, 1, -1}
2. Run a loop(loop variable ‘i’) from 0 till N.
3. Run another loop inside the above loop(loop variable ‘j’) from 0 till M.
4. After exiting all the above loops, we’ll now perform the following operations to get the board’s next state.
5. Run a loop(loop variable ‘i’) from 0 till N.
6. Return “board,” the next state of the board.
O(N * M), where N is the number of rows and M is the number of board columns.
While traversing the board, the outer loop runs N times, and the nested loop runs M times, and inside this loop, we are iterating on all the eight neighbors. Hence, the final time complexity will be O(N * M * 8) = O(N * M)
O(1)
As we are using constant memory space.