Problem
Given an mxn matrix, design a function that will print out the contents of the matrix in spiral format.
Spiral format means for a 5x5 matrix given below:
[ 1 2 3 4 5 ]
[ 6 7 8 9 0 ]
[ 1 2 3 4 5 ]
[ 6 7 8 9 0 ]
[ 1 2 3 4 5 ]
path taken is:
[ > > > > > ]
[ > > > > v ]
[ ^ ^ > v v ]
[ ^ ^ < < v ]
[ < < < < < ]
where ">" is going right, "v" going down, "<" is going left, "^" is going up.
The output is:
1 2 3 4 5 0 5 0 5 4 3 2 1 6 1 6 7 8 9 4 9 8 7 2 3
*/
Solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JamesChen
{
class PrintSpiralArray
{
static void PrintSpiral(int[ , ] arr)
{
int rows = arr.GetLength(0);
int cols = arr.GetLength(1);
int levels = (rows + 1) >> 1;
int i = 0;
int j = 0;
int k = 0;
while(k < levels)
{
i = k;
j = k;
while(j < rows - k)
{
Console.Write("{0, 4}", arr[i, j]);
j ++;
}
i ++;
j --;
while(i < cols - k)
{
Console.Write("{0, 4}", arr[i, j]);
i ++;
}
i --;
j --;
while(j > k - 1)
{
Console.Write("{0, 4}", arr[i, j]);
j --;
}
i --;
j ++;
while(i > k)
{
Console.Write("{0, 4}", arr[i, j]);
i --;
}
k++;
}
Console.WriteLine();
}
static void Main(string[] args)
{
for(int i = 1; i < 6; ++ i)
{
int[ , ] arr = new int[i, i];
Console.WriteLine("The array is ");
for(int j = 0; j < i; ++j)
{
for(int k = 0; k < i; ++k)
{
arr[j, k] = j * i + k;
Console.Write("{0, 4}", arr[j, k]);
}
Console.WriteLine();
}
Console.WriteLine("Print in spiral order");
PrintSpiral(arr);
Console.WriteLine("-----------------------");
}
}
}
}
Output
The array is
0
Print in spiral order
0
-----------------------
The array is
0 1
2 3
Print in spiral order
0 1 3 2
-----------------------
The array is
0 1 2
3 4 5
6 7 8
Print in spiral order
0 1 2 5 8 7 6 3 4
-----------------------
The array is
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
Print in spiral order
0 1 2 3 7 11 15 14 13 12 8 4 5 6 10 9
-----------------------
The array is
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
Print in spiral order
0 1 2 3 4 9 14 19 24 23 22 21 20 15 10 5 6 7 8 13 18 17 16 11 12
-----------------------
Press any key to continue . . .