Could u help me and correct my code
static void SolveAndDraw(int number)
{
// Create Dynamic List of list to
List<List<int>> matrix = new List<List<int>>();
// Intialize the inner lists
for (int j = 0; j < number; j++)
{
matrix.Add(new List<int>());
}
char direction = 'r';
int xPos = 0, yPos = 0;
int rightLimit = number - 1;
int leftLimit = 0;
int upLimit = 0;
int bottomLimit = number - 1;
for (int i = 1; i <= number * number; ++i)
{
// matrix[yPos][xPos] = i;
matrix[xPos].Insert(yPos, i);
switch (direction)
{
case 'r':
if (xPos < rightLimit)
{
++xPos;
}
else
{
direction = 'd';
++upLimit;
++yPos;
}
break;
case 'l':
if (xPos > leftLimit)
{
--xPos;
}
else
{
direction = 'u';
--bottomLimit;
--yPos;
}
break;
case 'u':
if (yPos > upLimit)
{
--yPos;
}
else
{
direction = 'r';
++leftLimit;
++xPos;
}
break;
case 'd':
if (yPos < bottomLimit)
{
++yPos;
}
else
{
direction = 'l';
--rightLimit;
--xPos;
}
break;
}
}
// Now, just dump the matrix contents to stdout
for (int i = 0; i < number; ++i)
{
for (int j = 0; j < number; ++j)
{
Console.Write("{0}\t", matrix[i][j]);
}
Console.Write("\n");
}
Console.ReadLine();
}
It crashes and gives the error:
Index must be within the bounds of the List.
Parameter name: index
Is that list of lists required, or can you use an array with 2 dimensions (you are passing the dimension through number, why do you need the lists?)