> For the complete documentation index, see [llms.txt](https://emmaguo100.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://emmaguo100.gitbook.io/leetcode/05-31-2022-566.-reshape-the-matrix.md).

# 05/31/2022 566. Reshape the Matrix

Method1: we get the element by row-by-row order. Initate m,n to 0. m is for the row and n is for col. Initiate the result 2d array with the r and c value. Scan the orginal matrix, set result\[m]\[n] = the current element, increment n. When n equals the c, we need set n to 0 again and increment m.

Time O(m \*n)

Space O(1)

```
// Some code
class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        int row = mat.length;
        int col = mat[0].length;
        if (row * col != r * c)
            return mat;
        int[][] result = new int[r][c];
        int m = 0;
        int n = 0;
        
        for (int i = 0; i < row; i++){
            for (int j = 0; j < col; j++){
                result[m][n] = mat[i][j];
                n++;
                if (n == c){
                    m++;
                    n = 0;
                }
            }
        }
        return result;
    }
}
```

Method 2:

use divide and modulus. For 2d array, it is represented in a 1-d array internally. We use count as the 1d array index, when it converts to 2d-array index, we use count/c as the row index and count%c as the column index.

Time O(n\*m)

Space O(1)

```
// Some code
//Using division and modulus
class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
        int rowOld = mat.length;
        int colOld = mat[0].length;
        if (rowOld == 0 || rowOld * colOld != r * c) return mat;
        int count = 0;
        int[][] result = new int[r][c];
        for (int i = 0; i < rowOld; i++){
            for (int j = 0; j < colOld; j++){
                result[count/c][count%c] = mat[i][j];
                count++;
            }
        }
        return result;
    }
}
```
