1. Count number of subMatrixes with all 1
// Step 1: Build row-wise consecutive 1s
for (int i = 0; i < m; i++) {
    for (int j = 0; j < n; j++) {
        if (mat[i][j] == 1) {
            rowOnes[i][j] = (j == 0) ? 1 : rowOnes[i][j - 1] + 1;
        }
    }
}

// Step 2: For each cell, go upwards and find minimum width to count rectangles
for (int j = 0; j < n; j++) {
    for (int i = 0; i < m; i++) {
        if (mat[i][j] == 1) {
            int minWidth = rowOnes[i][j];
            for (int k = i; k >= 0 && rowOnes[k][j] > 0; k--) {
                minWidth = Math.min(minWidth, rowOnes[k][j]);
                count += minWidth;
            }
        }
    }
}

return count;
}

2. Traversing in All Directions

  1. Spiral Matrix II

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

Example 1:

Input: n = 3
Output: [[1,2,3],[8,9,4],[7,6,5]]

Example 2:

Input: n = 1
Output: [[1]]

Constraints: