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.
Example 1:
Input: grid
= [[1,2,3],[4,5,6],[7,8,9]], k = 1
Output: [[9,1,2],[3,4,5],[6,7,8]]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class Shift2DGrid {public static void main(String[] args) {int[][] grid = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };int k = 1;grid = shiftGrid(grid, k);System.out.println(Arrays.deepToString(grid));}static int[][] shiftGrid(int[][] grid, int k) {int n = grid.length;int m = grid[0].length;int total = n * m;k = k % total;List<Integer> v = new ArrayList<Integer>();List<Integer> v1 = new ArrayList<Integer>();k = total - k;for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (k > 0) {v.add(grid[i][j]);k--;} else {v1.add(grid[i][j]);}}}int l = 0, l1 = 0;int len = v1.size();for (int i = 0; i < n; i++) {for (int j = 0; j < m; j++) {if (len > 0) {len--;grid[i][j] = v1.get(l++);} else {grid[i][j] = v.get(l1++);}}}return grid;}}
C++
#include <bits/stdc++.h>using namespace std;vector<vector<int>> shiftGrid(vector<vector<int>> &grid, int k){int n = grid.size();int m = grid[0].size();int total = n * m;k = k % total;vector<int> v, v1;k = total - k;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){if (k > 0){v.push_back(grid[i][j]);k--;}elsev1.push_back(grid[i][j]);}}int l = 0, l1 = 0;int len = v1.size();for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){if (len > 0){len--;grid[i][j] = v1[l++];}else{grid[i][j] = v[l1++];}}}return grid;}int main(){vector<vector<int>> grid = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};int k = 1;grid = shiftGrid(grid, k);cout << "[";for (int i = 0; i < grid.size(); i++){cout << "[";for (int j = 0; j < grid[i].size(); j++){cout << grid[i][j];if (j != grid[i].size() - 1)cout << ",";}cout << "]";if (i != grid.size() - 1)cout << ",";}cout << "]";return 0;}
No comments:
Post a Comment