# 59. Spiral Matrix II

### Leetcode

<https://leetcode.com/problems/spiral-matrix-ii/>

### 題目

Given a positive integer `n`, generate an `n x n` `matrix` filled with elements from `1` to `n2` in spiral order.

### 解答 <a href="#ti-jie" id="ti-jie"></a>

* **方法一**

如同 54. Spiral Matrix，設定四個方向(往右 -> 往下 -> 往左 -> 往上)，依序遍歷

```
var generateMatrix = function(n) {
    let startRow = 0;
    let startCol = 0;
    let endRow = n - 1;
    let endCol = n - 1;
    
    const result = Array.from({length: n}, () => Array(n));
    let number = 1;
    while(true) {
      for(let i=startCol; i<=endCol; i++) {
          result[startRow][i] = number++;
      }
      startRow++;
      if (number > n**2) break;
      
      for(let i=startRow; i<=endRow; i++) {
          result[i][endCol] = number++;
      }
      endCol--;
      if (number > n**2) break;
      
      for(let i=endCol; i>=startCol; i--) {
          result[endRow][i] = number++;
      }
      endRow--;
      if (number > n**2) break;
      
      for(let i=endRow; i>=startRow; i--) {
          result[i][startCol] = number++;
      }
      startCol++;
      if (number > n**2) break;
    }
    return result;
};
```

Runtime: 72 ms, faster than 78.29% of JavaScript online submissions for Spiral Matrix II.

Memory Usage: 39 MB, less than 32.56% of JavaScript online submissions for Spiral Matrix II.

### 測資

```
let n = 1;
n = 3;

console.log(generateMatrix(n));
```
