经常会出现在程序员的面试题中
旋转矩阵
直接贴代码:
namespace MyDemo1
{
enum Direction
{
LeftToRight,
UpToDown,
RightToLeft,
DownToUp
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入一个矩阵阶数");
int n = int.Parse(Console.ReadLine());
//输出方向
Direction dir = Direction.LeftToRight;
int[,] Arr = new int[n, n];
//i 代表行下标,j代表列下标
int i = -1, j = 0, Value = 1;
//最大行,最大列...
int maxRow = n, maxCol = n, minRow = -1, minCol = -1;
do
{
switch (dir)
{
case Direction.LeftToRight:
i++; //0
while (j < maxCol)
{
Arr[i, j] = Value;
Value++;
j++;
}
j--;//4
dir = Direction.UpToDown;
minRow++;
break;
case Direction.UpToDown:
i++; //1
while (i < maxRow)
{
Arr[i, j] = Value;
Value++;
i++;
}
i--;//4
dir = Direction.RightToLeft;
maxCol--;
break;
case Direction.RightToLeft:
j--; //3
while (j > minCol)
{
Arr[i, j] = Value;
Value++;
j--;
}
j++; //0
maxRow--;
dir = Direction.DownToUp;
break;
case Direction.DownToUp:
i--;//3
while (i > minRow)
{
Arr[i, j] = Value;
Value++;
i--;
}
j++;
minCol++;
dir = Direction.LeftToRight;
break;
}
} while (Value <= n * n);
int count = 0;
for (int a = 0; a < Arr.GetLength(0); a++)
{
for (int b = 0; b < Arr.GetLength(1); b++)
{
Console.Write(Arr[a,b]+" ");
count++;
if (count > n - 1)
{
count = 0;
Console.WriteLine();
}
}
}
}
}
}