Als Zuweisung muss ich eine spiralförmige Matrix erstellen, in der der Benutzer die Anzahl der Zeilen und die Anzahl der Spalten eingibt. Dies ist für weit mein Code (im ersten Jahr im College-Studien, so sein, nicht hart an mich)Spiralmatrix mit eingegebenen Zeilen und Spalten
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();
ich ein bisschen bin verloren, wie this.I wissen, wie die Matrix-Schleife mit die gleiche Anzahl für die Zeilen und Spalten, aber es sollte eine nicht-quadratische Matrix sein.
4 x 3 Matrix
8 9 10 1
7 12 11 2
6 5 4 3
5 x 2 Matrix
3 4
12 5
11 6
10 7
9 8
Ich suche noch ein bisschen Hilfe hier ... –