How to print an a 4x4 array in clockwise direction using C# [closed]
int numbs[4][4] =
1, 2, 3, 4
5, 6, 7, 8
9, 10, 11, 12
13, 14, 15, 16;
When i print it, it should print like this.
1 2 3 4, 8, 12,16, 15, 14, 13, 9, 5, 6, 7, 11, 10, (ie clockwise direction spiral):
---\ //first righ开发者_StackOverflow社区t, then down, left, up and repeat
/-\|
|-/|
\--/
Here's my stab at it:
static void Spiral(int[,] m)
{
int n = m.GetUpperBound(0);
for (int i = 0; i < n / 2; ++i)
{
for (int j = i; j <= n - i; ++j)
Console.Write(m[i, j] + " ");
for (int j = i + 1; j <= n - i; ++j)
Console.Write(m[j, n - i] + " ");
for (int j = i + 1; j <= n - i; ++j)
Console.Write(m[n - i, n - j] + " ");
for (int j = i + 1; j < n - i; ++j)
Console.Write(m[n - j, i] + " ");
}
Console.Write(m[n / 2, n / 2]+" ");
if (n % 2 == 1)
{
Console.Write(m[n / 2, n / 2+1] + " ");
Console.Write(m[n / 2+1, n / 2+1] + " ");
Console.Write(m[n / 2+1, n / 2] + " ");
}
}
static void Main(string[] args)
{
int[,] myArray = new int[,]{
{11, 12, 13, 14, 15},
{21, 22, 23, 24, 25},
{31, 32, 33, 34, 35},
{41, 42, 43, 44, 45},
{51, 52, 53, 54, 55}
};
Spiral(myArray);
}
The output is:
11 12 13 14 15 25 35 45 55 54 53 52 51 41 31 21 22 23 24 34 44 43 42 32 33
edit: Works for both even and odd sized square matrices now.
Do you have any specific technique that you are supposed to use for this exercise? Otherwise you can just write code that does that:
Console.WriteLine(theArray[0,0]);
Console.WriteLine(theArray[1,0]);
Console.WriteLine(theArray[2,0]);
Console.WriteLine(theArray[3,0]);
Console.WriteLine(theArray[3,1]);
Console.WriteLine(theArray[3,2]);
Console.WriteLine(theArray[3,3]);
Console.WriteLine(theArray[2,3]);
Console.WriteLine(theArray[1,3]);
Console.WriteLine(theArray[0,3]);
Console.WriteLine(theArray[0,2]);
Console.WriteLine(theArray[0,1]);
Console.WriteLine(theArray[1,1]);
Console.WriteLine(theArray[2,1]);
Console.WriteLine(theArray[2,2]);
Console.WriteLine(theArray[1,2]);
精彩评论