Following algorithm works by looking at the current row and column and deciding in which direction the next digit in the sequence should be placed. Once one round is completed the size of the pending matrix is calculated appropriately.

The same will be repeated until we are at the last element of the matrix.

- The algorithm makes decision base on row and column position while working thru the condition.
- The algorithm also keeps track of the number of rounds it is going to take to write the last number in the correct position in the matrix.

''' int[,] spiralMatrix = new int[n, n];

```
int row = 0;
int col = -1;
int start = 0;
int end = n * n;
int round = 0;
while (start != end)
{
if (row == round && col != n - 1)
{
col++;
}
else if (col == n - 1 && row != n - 1)
{
row++;
}
else if (row == n - 1 && col != round)
{
col--;
}
else if (row != round + 1 && col == round)
{
row--;
}
else
{
n--;
round++;
continue;
}
start++;
spiralMatrix[row, col] = start;
}
DisplayMatrix(spiralMatrix);
return spiralMatrix;
```

The complexity of the program is O(n*n) where n is the size of the matrix.