Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Shift 2D Grid in C++
Suppose we have one 2D grid of size m x n. We have another variable k. We have to shift the grid k times. The shift operation will be as follows
Element at grid G[i, j] moves to G[i, j + 1]
Element at grid G[i, n – 1] moves to G[i + 1, 0]
Element at grid G[m - 1, n – 1] moves to G[0, 0]
So if the grid is like −
| 1 | 2 | 3 |
| 4 | 5 | 6 |
| 7 | 8 | 9 |
The output will be −
| 9 | 1 | 2 |
| 3 | 4 | 5 |
| 6 | 7 | 8 |
To solve this, we will follow these steps −
The shift operation will take the matrix as input
n = number of rows, m := number of columns, x := bottom right element
-
for i := n – 1, down to 0
-
for j := m – 1 down to 0
if j = 0 and i > 0, then G[i, j] := G[i – 1, m - 1]
else if j > 0, then G[i, j] := G[i, j – 1]
-
G[0, 0] := x
Call the shift operation by the following rule −
-
while k is not 0
shift the grid G
decrease k by 1
return grid G
Example (C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << "[";
for(int j = 0; j <v[i].size(); j++){
cout << v[i][j] <<", ";
}
cout << "],";
}
cout << "]"<<endl;
}
class Solution {
public:
void shift(vector<vector<int>>& grid){
int n = grid.size();
int m = grid[0].size();
int x = grid[n-1][m-1];
for(int i = n-1; i>=0; i--){
for(int j = m-1;j>=0;j--){
if(j == 0 && i>0){
grid[i][j] = grid[i-1][m-1];
}
else if(j>0){
grid[i][j] = grid[i][j-1];
}
}
}
grid[0][0] = x;
}
vector<vector<int>> shiftGrid(vector<vector<int>>& g, int k) {
while(k--){
shift(g);
}
return g;
}
};
main(){
Solution ob;
vector<vector<int>> mat = {{1,2,3},{4,5,6},{7,8,9}};
print_vector(ob.shiftGrid(mat, 1));
}
Input
{{1,2,3},{4,5,6},{7,8,9}}
1
Output
[[9, 1, 2, ],[3, 4, 5, ],[6, 7, 8, ],]