Problem
Given a 2D grid of size m x n and an integer k. You need to shift the grid k times.
In one shift operation:
- Element at
grid[i][j]moves togrid[i][j + 1]. - Element at
grid[i][n - 1]moves togrid[i + 1][0]. - Element at
grid[m - 1][n - 1]moves togrid[0][0].
Return the 2D grid after applying shift operation k times.
Examples
Example 1:
$$ grid = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} \Longrightarrow \\ \begin{bmatrix} 9 & 1 & 2 \\ 3 & 4 & 5 \\ 6 & 7 & 8 \end{bmatrix} $$
| |
Example 2:
$$ grid = \begin{bmatrix} 3 & 8 & 1 & 9 \\ 19 & 7 & 2 & 5 \\ 4 & 6 & 11 & 10 \\ 12 & 0 & 21 & 13 \end{bmatrix} \\ \Longrightarrow \\ \begin{bmatrix} 13 & 3 & 8 & 1 \\ 9 & 19 & 7 & 2 \\ 5 & 4 & 6 & 11 \\ 10 & 12 & 0 & 21 \end{bmatrix} \\ \Longrightarrow \\ \begin{bmatrix} 21 & 13 & 3 & 8 \\ 1 & 9 & 19 & 7 \\ 2 & 5 & 4 & 6 \\ 11 & 10 & 12 & 0 \end{bmatrix} \\ $$
$$ \Longrightarrow \\ \begin{bmatrix} 0 & 21 & 13 & 3 \\ 8 & 1 & 9 & 19 \\ 7 & 2 & 5 & 4 \\ 6 & 11 & 10 & 12 \end{bmatrix} \\ \Longrightarrow \\ \begin{bmatrix} 12 & 0 & 21 & 13 \\ 3 & 8 & 1 & 9 \\ 19 & 7 & 2 & 5 \\ 4 & 6 & 11 & 10 \end{bmatrix} $$
| |
Example 3:
| |
Solution
Method 1 - Treat Matrix as 1D Array
We can easily convert this 2D matrix to 1D Array. Lets take example 1.
Element 1 in [0,0] will be at [0] in 1D array. Likewise, element 5 at [1,1] is at index [4] in 1D array.
So, any element in 2D array will be numRows * rowIndex + column
| |
We should also do k%size of 2D array.
Once we have the size, we need to convert back the 1D array to 2D Array:
| |
Method 2 - Using Arraylist Instead of Array Indexes
| |