> 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/set-matrix-zeroes.md).

# 矩阵置零

题目链接: <https://leetcode.cn/problems/set-matrix-zeroes>

## 解题思路：

1. 遍历矩阵，找到值为0的元素，将对应的行和列标记为需要置零
2. 遍历需要置零的行和列的记录表，将对应行及对应列的所有元素置零

```go
func setZeroes(matrix [][]int) {
	m, n := len(matrix), len(matrix[0])
	if matrix == nil || m == 0 || (m == 1 && n == 1) {
		return
	}
	zeroX, zeroY := make([]int, m), make([]int, n)
	for x, row := range matrix {
		for y, cell := range row {
			if cell == 0 {
				zeroX[x] = 1
				zeroY[y] = 1
			}
		}
	}
	for x, item := range zeroX {
		if item == 1 {
			for y := 0; y < n; y++ {
				matrix[x][y] = 0
			}
		}
	}

	for y, item := range zeroY {
		if item == 1 {
			for x := 0; x < m; x++ {
				matrix[x][y] = 0
			}
		}
	}
}
```

## 复杂度分析

* **时间复杂度：** 时间复杂度为$$O(m\*n)$$,$$m$$为矩阵的行数,$$n$$为矩阵的列数
* **空间复杂度：** 空间复杂度为$$O(m\*n)$$,$$m$$为矩阵的行数,$$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/set-matrix-zeroes.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.
