作业帮 > 综合 > 作业

一个旋转矩阵问题同学给了我一个题目就是输入一个正整数n 比如n=4输出一个n*n的矩阵如下 1 2 3 412 13 1

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/04/27 18:52:36
一个旋转矩阵问题
同学给了我一个题目就是输入一个正整数n 比如n=4
输出一个n*n的矩阵如下
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
这个应该怎么写呢……
递归写法,理论上有输入上限,不过一般也不会有那么大的输入
没有处理格式,没有处理输入,只写了算法...
class Program
{
private static void Fill(int[,] matrix,Direction direction,int start,
int rows,int cols,int rowOffset,int colOffset)
{
if (rows == 0 || cols == 0) return;
switch (direction)
{
case Direction.Left:
for (int n = cols; n > 0; )
matrix[rowOffset + rows - 1,colOffset + --n] = ++start;
Fill(matrix,Direction.Up,start,rows - 1,cols,rowOffset,colOffset);
break;
case Direction.Right:
for (int n = 0; n < cols; ++n)
matrix[rowOffset,colOffset + n] = ++start;
Fill(matrix,Direction.Down,start,rows - 1,cols,rowOffset + 1,colOffset);
break;
case Direction.Up:
for (int n = rows; n > 0; )
matrix[rowOffset + --n,colOffset] = ++start;
Fill(matrix,Direction.Right,start,rows,cols - 1,rowOffset,colOffset + 1);
break;
case Direction.Down:
for (int n = 0; n < rows; ++n)
matrix[rowOffset + n,colOffset + cols - 1] = ++start;
Fill(matrix,Direction.Left,start,rows,cols - 1,rowOffset,colOffset);
break;
}
}
enum Direction { Left,Right,Up,Down };
static void Main(string[] args)
{
int n = 4;
int[,] matrix = new int[n,n];
Fill(matrix,Direction.Right,0,4,4,0,0);
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; ++j)
{
Console.Write(matrix[i,j] + " ");
}
Console.WriteLine();
}
Console.WriteLine();
}
}