Fill a Square with Consecutive Spiral Values

Quick Overview

Construct a square matrix filled from 1 to n squared along a clockwise inward spiral.

Fill a Square with Consecutive Spiral Values

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

### Problem Create an `n` by `n` integer matrix containing each integer from 1 through `n^2` once. Put the numbers in clockwise spiral order, starting with 1 in the top-left corner and moving right across the top row before turning down and inward. ```cpp vector<vector<int>> generateMatrix(int n); ``` ### Examples ```text Input: n = 2 Output: [[1,2],[4,3]] ``` ```text Input: n = 4 Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]] ``` ### Constraints - `1 <= n <= 20`. - Return a square matrix; this interface has no existing matrix argument to mutate.

Overview: Construct a square matrix filled from 1 to n squared along a clockwise inward spiral.

Amazon logo
Amazon
Date not reported
mediumSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Create an n by n integer matrix containing each integer from 1 through n^2 once. Put the numbers in clockwise spiral order, starting with 1 in the top-left corner and moving right across the top row before turning down and inward.

vector<vector<int>> generateMatrix(int n);

Examples

Input: n = 2
Output: [[1,2],[4,3]]
Input: n = 4
Output: [[1,2,3,4],[12,13,14,5],[11,16,15,6],[10,9,8,7]]

Constraints

  • 1 <= n <= 20 .
  • Return a square matrix; this interface has no existing matrix argument to mutate.