我遇到與此作業有關的問題。我要打印一個不能是方形的螺旋矩陣,換句話說,用戶應該輸入行數和列數。非正方形螺旋矩陣打印不正確
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();
}
我的問題目前不在印刷,並在同一螺旋被打印。換句話說,這個螺旋線有點混亂。 如果我運行代碼和行6號,並輸入4,因爲我得到的列數如下:
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))'should如果(方向==「右」&&(col> m - 1 || matrix [row,col]!= 0))(** m **而不是n) – Fildor
@YairHalberstadt我猜螺旋要走了「向內」而不是「向外」。 – Fildor