私はこの課題に問題があります。私は四角形ではない螺線形の行列を印刷します。つまり、ユーザーは行と列の数を入力する必要があります。正方形でないスパイラルマトリックスが正しく印刷されない
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
私は間違って何をしているのですか?私は "右"、あなたの境界はm
あるべきために推測
if (direction == "right" && (col > n - 1 || matrix[row, col] != 0))
if (direction == "down" && (row > n - 1 || matrix[row, col] != 0))
:
開始のために配列の中心から始まっていない –
私は 'if(direction ==" right "&&(col> n - 1 ||行列[row、col]!= 0))' (方向の== "右" &&(col> m - 1 ||行列[行、col]!= 0)) '(** mの代わりにn **) – Fildor
@YairHalberstadt私はらせんが起こっていると思う「内向き」ではなく「外向き」である。 – Fildor