1. Copy Grid Simulation (Brute Force)
Intuition
Rules: 1. Any live cell with < 2 live neighbors dies. 2. Any live cell with 2 or 3 live neighbors lives. 3. Any live cell with > 3 live neighbors dies. 4. Any dead cell with exactly 3 live neighbors becomes live. Read neighbor counts from copy and write next state to board.
When to apply: Use to verify Conway's game rules without state contamination.
Copy Grid Next State Trace
2 of 2 questions left todayGlider sub-pattern: live cells at (0,1), (1,2), (2,0), (2,1), (2,2)
Glider sub-pattern: live cells at (0,1), (1,2), (2,0), (2,1), (2,2). Copy created.
import java.util.*; public class Main { public static class Solution { public void gameOfLife(int[][] board) { int m = board.length, n = board[0].length; int[][] copy = new int[m][n]; for (int r = 0; r < m; r++) { for (int c = 0; c < n; c++) copy[r][c] = board[r][c]; } int[] dirs = {-1, 0, 1}; for (int r = 0; r < m; r++) { for (int c = 0; c < n; c++) { int liveNeighbors = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (dirs[i] == 0 && dirs[j] == 0) continue; int nr = r + dirs[i], nc = c + dirs[j]; if (nr >= 0 && nr < m && nc >= 0 && nc < n && copy[nr][nc] == 1) { liveNeighbors++; } } } if (copy[r][c] == 1 && (liveNeighbors < 2 || liveNeighbors > 3)) { board[r][c] = 0; } else if (copy[r][c] == 0 && liveNeighbors == 3) { board[r][c] = 1; } } } } } public static void main(String[] args) { Solution sol = new Solution(); int[][] board = { {0, 1, 0}, {0, 0, 1}, {1, 1, 1}, {0, 0, 0} }; sol.gameOfLife(board); System.out.println("Next Gen: " + Arrays.deepToString(board)); }}Time & Space Complexity
- Time complexity:
O(m * n)— Count neighbors for each of m*n cells in 8 directions. - Space complexity:
O(m * n)— O(m * n) auxiliary board copy.
Why Brute Force Doesn't Scale:
For large grid simulations, duplicating memory causes unnecessary cache misses and garbage collection overhead.
2-bit encoding reduces space complexity from O(M * N) to O(1) with 0 memory allocations.