Skip to main content
Back to problems
Leetcode
Medium
Arrays
Matrices
Backtracking
Fill A Special Grid

Construct a grid by placing values so that a special row-and-column condition is satisfied.

Acceptance 0%
Problem Statement

Problem

You are given an integer nn. Build an n×nn \times n grid using the values from $0toton^2 - 1$ exactly once each.

The grid must be filled so that the arrangement follows a special rule based on the recursive structure of the grid: values are assigned in groups to sub-squares, and each smaller square is filled consistently according to the same rule until the grid is complete.

Your task is to return any valid grid that satisfies the rule.

Notes

  • Every number from $0toton^2 - 1$ must appear exactly once.
  • The grid must be nn rows by nn columns.
  • If multiple valid grids exist, return any one of them.

Input Format

  • An integer n describing the side length of the grid.

Output Format

  • Return an n x n integer grid containing every value from 0 to n^2 - 1 exactly once.

Constraints

  • 1n321 \le n \le 32
  • All values in the output must be integers in the range [0,n21][0, n^2 - 1].
  • Each value must appear exactly once.
Examples
Sample cases returned by the problem API.

Example 1

Input

n = 2

Output

[[0,1],[2,3]]

Explanation

This is one valid 2x2 grid using each value exactly once.

Example 2

Input

n = 3

Output

[[0,1,2],[3,4,5],[6,7,8]]

Explanation

This is another valid grid example that uses every number from 0 to 8 exactly once.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.