
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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5int** shiftGrid(int** grid, int gridSize, int* gridColSize, int k, int* returnSize, int** returnColumnSizes) {
6 int m = gridSize, n = *gridColSize;
7 int total = m * n;
8 *returnSize = m;
9 int** result = malloc(m * sizeof(int*));
10 *returnColumnSizes = malloc(m * sizeof(int));
11 for (int i = 0; i < m; i++) {
12 result[i] = malloc(n * sizeof(int));
13 (*returnColumnSizes)[i] = n;
14 }
15 k = k % total;
16 for (int i = 0; i < m; i++) {
17 for (int j = 0; j < n; j++) {
18 int index1D = ((i * n + j) + total - k) % total;
19 int destRow = index1D / n;
20 int destCol = index1D % n;
21 result[destRow][destCol] = grid[i][j];
22 }
23 }
24 return result;
25}This C solution first calculates the equivalent shift for the 1D representation of the grid. The nested loop traverses each element in the current 2D grid and calculates its new position in the shifted grid using the offset calculated with the modulo operation.
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.
1#
The C version for direct mapping ensures each element’s target location is computed directly, with careful attention to index wrap-around using modulus.