Today, I saw an interview question that a netizen encountered. I thought it was quite interesting. I wrote the algorithm:
Question: print the following matrix
1 2 3 4 5 6
20 21 22 23 24 7
19 32 33 34 25 8
18 31 36 35 26 9
17 30 29 28 27 10
16 15 14 13 12 11
The Code is as follows:
Class program
{
Static void Main (string [] args)
{
New program (). Run ();
}
// Number of times in each direction
Int right = 1;
Int down = 0;
Int left = 0;
Int up = 0;
Int n = 6; // matrix N * N
// Matrix rows and columns
Int row = 0;
Int col = 0;
Direction direction = Direction. Right;
Int [,] a = new int [6, 6];
Enum Direction
{
Right = 0,
Down = 1,
Left = 2,
Up = 3
}
Void Run ()
{
For (int I = 1; I <= n * n; I ++)
{
A [row, col] = I;
Fang ();
}
For (int I = 0; I <6; I ++)
{
For (int j = 0; j <6; j ++)
{
Console. Write ("{0}", a [I, j]);
}
Console. Write ("\ n ");
}
Console. Read ();
}
Void Fang ()
{
Switch (direction)
{
Case Direction. Right:
If (col <n-down-1)
{
Col ++;
}
Else
{
Direction = Direction. Down;
Row ++;
Down ++;
}
Break;
Case Direction. Down:
If (row <n-left-1)
{
Row ++;
}
Else
{
Direction = Direction. Left;
Col --;
Left ++;
}
Break;
Case Direction. Left:
If (col> up)
{
Col --;
}
Else
{
Direction = Direction. Up;
Up ++;
Row --;
}
Break;
Case Direction. Up:
If (row> right)
{
Row --;
}
Else
{
Direction = Direction. Right;
Right ++;
Col ++;
}
Break;
}
}
}