The spiral matrix problem involves generating a matrix in a spiral order. Given a matrix size (m x n), the goal is to fill the matrix with numbers from 1 to m*n in a spiral pattern.
Example
For a 3x3 matrix, the spiral order would look like this:
1 2 3
8 9 4
7 6 5
C# Solution
Here’s a C# implementation to generate a spiral matrix:
using System;
public class SpiralMatrix
{
public static int[,] GenerateSpiralMatrix(int m, int n)
{
int[,] matrix = new int[m, n];
int left = 0, right = n - 1, top = 0, bottom = m - 1;
int number = 1;
while (left <= right && top <= bottom)
{
// Fill top row
for (int i = left; i <= right; i++)
{
matrix[top, i] = number++;
}
top++;
// Fill right column
for (int i = top; i <= bottom; i++)
{
matrix[i, right] = number++;
}
right--;
// Fill bottom row
if (top <= bottom)
{
for (int i = right; i >= left; i--)
{
matrix[bottom, i] = number++;
}
bottom--;
}
// Fill left column
if (left <= right)
{
for (int i = bottom; i >= top; i--)
{
matrix[i, left] = number++;
}
left++;
}
}
return matrix;
}
public static void PrintMatrix(int[,] matrix)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write(matrix[i, j] + "\t");
}
Console.WriteLine();
}
}
public static void Main(string[] args)
{
int m = 3; // number of rows
int n = 3; // number of columns
int[,] spiralMatrix = GenerateSpiralMatrix(m, n);
PrintMatrix(spiralMatrix);
}
}
Explanation
-
Initialization:
- A 2D array
matrix
is created to hold the values. - Four boundaries (
left
,right
,top
,bottom
) are initialized to control the direction of filling. - A variable
number
is initialized to keep track of the current number to fill in the matrix.
- A 2D array
-
Filling the Matrix:
- A
while
loop runs until the boundaries cross each other. - Each iteration fills one layer of the matrix:
- Fill the top row from left to right.
- Fill the right column from top to bottom.
- Fill the bottom row from right to left (only if still within bounds).
- Fill the left column from bottom to top (only if still within bounds).
- After each direction is filled, the corresponding boundary is adjusted.
- A
-
Printing the Matrix:
- The
PrintMatrix
method is used to display the filled matrix.
- The
Output
When you run the program with a 3x3 matrix, the output will be:
1 2 3
8 9 4
7 6 5
Complexity
- Time Complexity: O(m * n) since every element is filled once.
- Space Complexity: O(1) for the algorithm itself, but O(m * n) for storing the matrix.
This approach efficiently fills a matrix in a spiral order while keeping the code clear and easy to understand.