# 867. Transpose Matrix

[LeetCode](https://leetcode.com/problems/transpose-matrix/)

```
Given a matrix A, return the transpose of A.

The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix.
```

![](/files/-LuKC4uqdFUK5BWrgiAC)

```
Example 1:

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

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

### 怎麼解

Matrix 題目都要先找 pattern 再解，所以這一題原本的 index 是以下

```
[0, 0], [0, 1], [0, 2]
[1, 0], [1, 1], [1, 2]
[2, 0], [2, 1], [2, 2]
```

會變以下，然後重要的是找出 pattern

```
// i 指 第一個 index, j 是第二個 index
[0, 0], [1, 0], [2, 0] // row 0
[0, 1], [1, 1], [2, 1] // row 1
[0, 0], [1, 2], [2, 2] // row 2
```

觀察 j 就是固定 row 的數字，而 i 都是 0, 1, 2&#x20;

```javascript
var transpose = function(lists) {
  // 反轉過後原本 Row 會變 Column，Column 變 Row
  let columns = matrix[0].length;
  let rows = matrix.length;
  let newMatrix = []


  for(let y=0; y< columns; y++){
      let tmp = []
      for(let x=0; x< rows; x++){
          tmp.push(matrix[x][y])
      }
      newMatrix.push(tmp)
   }

    return newMatrix
};

console.log(transpose([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]))
```


---

# Agent Instructions: 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:

```
GET https://hannahpun.gitbook.io/leetcode-note/matrix/867.-transpose-matrix.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
