---
# System prepended metadata

title: 867. Transpose Matrix
tags: [Leetcode, python, array, c++, easy]

---

###### tags: `Leetcode` `easy` `array` `python` `c++`

# 867. Transpose Matrix

## [題目連結:] https://leetcode.com/problems/transpose-matrix/description/

## 題目:
Given a 2D integer array``` matrix```, return the **transpose** of ```matrix```.

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

![](https://i.imgur.com/Tq9DZ0t.png)

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

## 解題想法:
* 將matrix進行transpose
    * 行列位置交換即可

## Python:
``` python=
class Solution(object):
    def transpose(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[List[int]]
        """
        row=len(matrix)
        col=len(matrix[0])
        res=[ [ 0 for _ in range(row)] for _ in range(col)]
        for i in range(row):
            for j in range(col):
                res[j][i]=matrix[i][j]
        return res
```

## C++:
``` cpp=
class Solution {
public:
    vector<vector<int>> transpose(vector<vector<int>>& matrix) {
        int row=matrix.size();
        int col=matrix[0].size();
        //二維創建注意初始內容
        vector<vector<int>> res(col, vector<int>(row));
        for (int i=0; i<row; i++){
            for (int j=0; j<col; j++){
                res[j][i]=matrix[i][j];
            }
        }
        return res;
    }
};
```