1. Visited Matrix Direction Simulation (Brute Force)
Intuition
Maintain current position (r, c) and direction pointer (dr, dc) cycling through right (0, 1), down (1, 0), left (0, -1), up (-1, 0). Before moving, check if the next cell is out of bounds or already visited. If so, rotate direction 90 degrees clockwise.
When to apply: Use to understand state machine direction turning on 2D grids.
Direction Simulation Trace
2 of 2 questions left todayMatrix 3x3
Matrix 3x3. Start at (0, 0) facing RIGHT. Add 1 to spiral.
import java.util.*; public class Main { public static class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); if (matrix == null || matrix.length == 0) return res; int m = matrix.length, n = matrix[0].length; boolean[][] visited = new boolean[m][n]; int[] dr = {0, 1, 0, -1}; int[] dc = {1, 0, -1, 0}; int r = 0, c = 0, di = 0; for (int i = 0; i < m * n; i++) { res.add(matrix[r][c]); visited[r][c] = true; int cr = r + dr[di]; int cc = c + dc[di]; if (cr >= 0 && cr < m && cc >= 0 && cc < n && !visited[cr][cc]) { r = cr; c = cc; } else { di = (di + 1) % 4; r += dr[di]; c += dc[di]; } } return res; } } public static void main(String[] args) { Solution sol = new Solution(); int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println("Spiral Order: " + sol.spiralOrder(matrix)); }}Time & Space Complexity
- Time complexity:
O(m * n)— Visits every cell exactly once, doing O(1) checks per step. - Space complexity:
O(m * n)— O(m * n) auxiliary 2D boolean matrix to store visited states.
Why Brute Force Doesn't Scale:
For N = 105, quadratic O(N2) approaches require ~1010 operations, exceeding the standard 1-second CPU budget.
The optimal approach processes N elements in a single or logarithmic pass, completing in under 10ms with minimal memory footprint.