
Sponsored
Sponsored
Transform the 2D grid into a 1D list: The problem of shifting all elements in a 2D grid can be simplified by flattening the grid into a 1D array. This enables easier shifting and indexing.
Shift the 1D Array: Determine the actual number of shifts needed by computing k % (m * n) to avoid redundant full rotations. Then partition and concatenate the 1D array accordingly to achieve the desired shift.
Transform back to 2D Grid: Finally, map the shifted 1D list back to the original 2D grid layout.
Time Complexity: O(m * n) since we access each grid element once.
Space Complexity: O(m * n) needed for the result grid storage.
1public class Solution {
2 public IList<IList<int>> ShiftGrid(int[][] grid, int k) {
3 int m = grid.Length, n = grid[0].Length;
4 int total = m * n;
5 k = k % total;
6 int[] flatGrid = new int[total];
7 for (int i = 0; i < m; i++) {
8 for (int j = 0; j < n; j++) {
9 flatGrid[i * n + j] = grid[i][j];
10 }
11 }
12 int[] shiftedGrid = new int[total];
13 Array.Copy(flatGrid, total - k, shiftedGrid, 0, k);
14 Array.Copy(flatGrid, 0, shiftedGrid, k, total - k);
15 IList<IList<int>> result = new List<IList<int>>();
16 for (int i = 0; i < m; i++) {
17 List<int> row = new List<int>();
18 for (int j = 0; j < n; j++) {
19 row.Add(shiftedGrid[i * n + j]);
20 }
21 result.Add(row);
22 }
23 return result;
24 }
25}C# solution involves copying parts of an array using built-in Array methods to achieve the same rotation effect efficiently, followed by constructing the resulting 2D grid.
Calculate Direct Position Mapping: Instead of flattening, calculate the direct position mapping for shifted elements. This avoids the extra space used by intermediate lists.
Perform Element-wise Placement: Iterate through elements and directly place them in their new calculated positions.
Time Complexity: O(m * n).
Space Complexity: O(m * n) for the shifted result.
1JavaScript calculates and directly reallocates values using direct index transformations within the new array during iteration.