AlgoViz

Pattern 22

Medium

Concentric number square

Problem

Print a concentric-number square (rings counting inward) for a given size n.

In simple words

Use one loop for the rows and another for what goes in each row to draw the shape.

The idea

Each cell prints how many rings it sits from the outside, which is its distance to the nearest edge. Computing that as one min() of four distances turns a fiddly-looking picture into a one-line formula.

The trick

  • Value = n - min(i, j, sideLength-1-i, sideLength-1-j) with 0-based indices.
  • The grid is (2n-1) x (2n-1) for n rings.
rows7

Step 1 of 9. Concentric squares: each ring counts inward n..1. rows 7.

1/9
Optimal
timeO(n^2)spaceO(1)
1// n = 4 produces:2// 4 4 4 4 4 4 43// 4 3 3 3 3 3 44// 4 3 2 2 2 3 45// 4 3 2 1 2 3 46// 4 3 2 2 2 3 47// 4 3 3 3 3 3 48// 4 4 4 4 4 4 49 10size = 2n-111for i in 0..size-1:12  for j in 0..size-1:13    print n - min(i, j, size-1-i, size-1-j)14  newline

Input

grid
7 × 7

Memory

rows
7

Output

printed rows
rows
7

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Example

Input:
n = 4
Output:
4 4 4 4 4 4 4 / 4 3 3 3 3 3 4 / 4 3 2 2 2 3 4 / 4 3 2 1 2 3 4 / 4 3 2 2 2 3 4 / 4 3 3 3 3 3 4 / 4 4 4 4 4 4 4

Finished the walkthrough? Add it to your streak.