> For the complete documentation index, see [llms.txt](https://leetcodebook-1.gitbook.io/top-interview-150/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leetcodebook-1.gitbook.io/top-interview-150/matrix/rotate-image.md).

# 旋转矩阵

题目链接: <https://leetcode.cn/problems/rotate-image/>

## 解题思路：

1. 矩阵旋转时，原有的`(row,coll)`位置的元素经过旋转，会变换到`(coll,n-row-1)`的位置
2. 所以我们可以逐行遍历矩阵，将每行元素旋转复制到一个临时矩阵中，在把最终结果复制回原矩阵

```go
func rotate(matrix [][]int) {
	if matrix == nil || len(matrix) == 0 || len(matrix) == 1 {
		return
	}
	n := len(matrix)
	tmp := make([][]int, n)
	for idx := range tmp {
		tmp[idx] = make([]int, n)
	}
	for i, item := range matrix {
		for j, cell := range item {
			tmp[j][n-i-1] = cell
		}
	}
	copy(matrix, tmp)
}
```

## 复杂度分析

* **时间复杂度：** 时间复杂度为$$O(n^2)$$,$$n$$为矩阵的行数
* **空间复杂度：** 空间复杂度为$$O(n^2)$$,$$n$$为矩阵的行数


---

# 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://leetcodebook-1.gitbook.io/top-interview-150/matrix/rotate-image.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.
