Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order in C++

Input: 3

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

Before looking into the solution, I recommend you to please go through print matrix in spiral order solution. These two solutions are very similar.

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Solution in C++

/*
* File     : fill_matrix_spiral_order.cpp
* Author   : ajay.thousand@gmail.com
* Copyright: @ prodevelopertutorial.com
*/
#include<iostream>
#include<vector>

using namespace std;

vector<vector<int> > generate_spiral_matrix(int n) 
{
	//Declaration of 2D vector.
    vector<vector<int>> result_matrix(n,vector<int>(n,0));

	// Normal Case
	int rowStart = 0;
	int rowEnd = n-1;
	int colStart = 0;
	int colEnd = n-1;
	int num = 1;

	while (rowStart <= rowEnd && colStart <= colEnd) 
	{
		for (int i = colStart; i <= colEnd; i ++) // 1. horizonal, left to right
		{
			result_matrix[rowStart][i] = num ++; 
		}
		rowStart ++;

		for (int i = rowStart; i <= rowEnd; i ++) // 2. vertical, top to bottom
		{
			result_matrix[i][colEnd] = num ++; 
		}
		colEnd --;

		for (int i = colEnd; i >= colStart; i --)  // 3. horizonal, right to left 
		{
			if (rowStart <= rowEnd)
				result_matrix[rowEnd][i] = num ++;
		}
		rowEnd --;

		for (int i = rowEnd; i >= rowStart; i --)  // 4. vertical, bottom to  top 
		{
			if (colStart <= colEnd)
                    result_matrix[i][colStart] = num ++;
        }
            colStart ++;
    }
        
        return result_matrix;
}    

int main() 
{
	int n = 3;

	//Declare a 2d vector to get the result
	vector<vector<int> > result_matrix = generate_spiral_matrix(n);

	cout<< "Result matrix is : "<<endl;
	for (int i = 0; i < n; i++) 
	{
		for (int j = 0; j < n; j++)
			cout << result_matrix[i][j] << ' ';
		cout << endl;
	}
}

 

Output:

Result matrix is :
1 2 3
8 9 4
7 6 5

For N = 3, below is the trace of the matrix it is generated.

Pass 1:
horizontal, left to right for loop
1 0 0
0 0 0
0 0 0

Pass 2:
horizontal, left to right for loop
1 2 0
0 0 0
0 0 0

Pass 3:

horizontal, left to right for loop
1 2 3
0 0 0
0 0 0

Pass 4:

vertical, top to bottom for loop
1 2 3
0 0 4
0 0 0

Pass 5:

vertical, top to bottom for loop
1 2 3
0 0 4
0 0 5

Pass 6:

horizontal, right to left for loop
1 2 3
0 0 4
0 6 5

Pass 7:

horizontal, right to left for loop
1 2 3
0 0 4
7 6 5

Pass 8:

vertical, bottom to top for loop
1 2 3
8 0 4
7 6 5

Pass 9:

horizontal, left to right for loop
1 2 3
8 9 4
7 6 5

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *