> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/59.spiral_matrix_ii.md).

# 59.Spiral Matrix II

**59.Spiral Matrix II**

难度:Medium

> Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

Example:

```
Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
```

从起点位置开始，一次连续放置数字，到头了或者前面的数字已经被放过了，则开始转向。建立一个方向向量，每次到头换一次，知道所有的`n*n`个数被放满。

```
class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n,vector<int>(n,0));
        res[0][0]=1;
       // if(n==1) return  res;
        int cur=2;
        vector<vector<int>> direct={{0,1}, {1,0},{0,-1}, {-1,0}};
        vector<int > start = {0,0};
        vector<int> p=direct[0];
        int pr=0;
        int N=n*n;
        while(cur<=N) 
        {
            int indx = start[0]+p[0] ;
            int indy = start[1]+p[1] ;
           // cout<<cur<<"  "<< start[0]+p[0] << "  "<<start[1]+p[1]<<endl;
            if(indx<0 || indx >=n || indy <0 || indy >=n || res[indx][indy] )
            {
                pr = (pr+1)%4;
                p = direct[pr];

            }
            else
            {
                res[indx][indy] =cur++;
                start[0]=indx;
                start[1] = indy;

            }


        }
        return res;
        
    }
};
```

> 执行用时 :8 ms, 在所有 C++ 提交中击败了68.59%的用户\
> 内存消耗 :9 MB, 在所有 C++ 提交中击败了42.07%的用户


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/59.spiral_matrix_ii.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
