Ich habe Probleme mit dieser Aufgabe, die ich habe. Ich soll eine Spiralmatrix drucken, die nicht quadratisch sein kann, dh der Benutzer sollte die Anzahl der Zeilen und Spalten eingeben.Nicht quadratische Spiralmatrix, die nicht korrekt gedruckt wird
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();
}
Mein Problem ist derzeit, dass nicht gedruckt wird und gleichzeitig in einer Spirale gedruckt wird. Mit anderen Worten, die Spirale ist irgendwie durcheinander. Wenn ich den Code ausführen und geben Sie 4 als die Anzahl der Zeilen und 6 als die Anzahl der Spalten ich folgendes:
1 2 3 4 0 24
12 13 14 5 0 23
11 16 17 18 19 22
10 9 8 7 20 21
Was mache ich falsch?
Sie starten nicht in der Mitte des Arrays für einen Start –
Ich denke 'if (Richtung ==" rechts "&& (col> n - 1 || Matrix [Zeile, col]! = 0))' sollte sei 'if (direction ==" rechts "&& (col> m - 1 || matrix [row, col]! = 0))' (** m ** statt n) – Fildor
@YairHalberstadt Ich schätze, die Spirale geht "nach innen" nicht "nach außen". – Fildor