【发布时间】:2017-09-13 11:36:37
【问题描述】:
我的这个作业有问题。我要打印一个不能为正方形的螺旋矩阵,换句话说,用户应该输入行数和列数。
Console.Write("Enter n: ");
int n = int.Parse(Console.ReadLine());
Console.Write("Enter m: ");
int m = int.Parse(Console.ReadLine());
int[,] matrix = new int[n,m];
int row = 0;
int col = 0;
string direction = "right";
int maxRotations = n * m;
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--;
}
}
// displej matrica
for (int r = 0; r < n; r++)
{
for (int c = 0; c < m ; c++)
{
Console.Write("{0,4}", matrix[r,c]);
}
Console.WriteLine();
}
Console.ReadLine();
}
我目前的问题是不是打印,同时是螺旋打印。换句话说,螺旋有点混乱。 如果我运行代码并输入 4 作为行数,输入 6 作为列数,我会得到以下结果:
1 2 3 4 0 24
12 13 14 5 0 23
11 16 17 18 19 22
10 9 8 7 20 21
我做错了什么?
【问题讨论】:
-
你不是从数组的中心开始的
-
我认为
if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))应该是if (direction == "right" && (col > m - 1 || matrix[row, col] != 0))(m 而不是n) -
@YairHalberstadt 我猜螺旋正在“向内”而不是“向外”。
-
@Fildor。如果你从 0,0 开始,你就不能有一个螺旋矩阵而不超出数组的边界!
-
啊,它是向内而不是向外!刚刚明白你的意思!