【发布时间】:2017-09-07 14:00:00
【问题描述】:
作为一项任务,我必须创建一个螺旋矩阵,用户在其中输入行数和列数。 这是我迄今为止的代码(大学学习的第一年,所以不要对我太苛刻)
Console.Write("Enter n: ");
int n = int.Parse(Console.ReadLine());
int[,] matrix = new int[n, n];
int row = 0;
int col = 0;
string direction = "right";
int maxRotations = n * n;
for (int i = 1; i <= maxRotations; i++)
{
if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
{
direction = "down";
col--;
row++;
}
if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
{
direction = "left";
row--;
col--;
}
if (direction == "left" && (col < 0 || matrix[row, col] != 0))
{
direction = "up";
col++;
row--;
}
if (direction == "up" && row < 0 || matrix[row, col] != 0)
{
direction = "right";
row++;
col++;
}
matrix[row, col] = i;
if (direction == "right")
{
col++;
}
if (direction == "down")
{
row++;
}
if (direction == "left")
{
col--;
}
if (direction == "up")
{
row--;
}
}
// display matrica
for (int r = 0; r < n; r++)
{
for (int c = 0; c < n; c++)
{
Console.Write("{0,4}", matrix[r, c]);
}
Console.WriteLine();
}
Console.ReadLine();
我对如何做到这一点有点迷茫。我知道如何用相同的行数和列数循环矩阵,但它应该是一个非方阵。
4 x 3 矩阵
8 9 10 1
7 12 11 2
6 5 4 3
5 x 2 矩阵
3 4
12 5
11 6
10 7
9 8
【问题讨论】:
-
我仍然在这里寻求帮助...