Shift 2D Grid In C++ - C++ Programming Tutorial
C++ Course / Miscellaneous / Shift 2D Grid In C++

Shift 2D Grid In C++

BLUF: Mastering Shift 2D Grid In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Shift 2D Grid In C++

C++ is renowned for its efficiency. Learn how Shift 2D Grid In C++ enables low-level control and high-performance computing in the tutorial below.

In this tutorial, we will explore the process of shifting a 2D Grid in C++ along with accompanying illustrations.

Introduction:

In C++, when we shift a 2D grid, we are essentially displacing each element within it in a specified direction, be it vertically or horizontally. This technique is commonly employed in various computational tasks such as image processing, matrix operations, and algorithms based on grids. By rearranging the grid, we can replicate motions, create animations, and effectively tackle specific challenges.

We commonly employ loops with embedded elements to iterate through the grid and adjust its elements as needed to achieve the shifting process. In C++, a vector of vectors is often utilized to depict a 2D grid, where each internal vector represents a row of the grid. This particular data structure enables convenient access to individual elements and offers versatile manipulation capabilities.

Flattening a 2D grid involves converting it into a 1D array before reshaping it back into a 2D grid with the applied displacement operation. This simplifies the management of 2D indices and eases the shifting procedure. Moreover, rotating the pieces of the flattened grid can be done efficiently to achieve the desired shift through the utilization of methods like reverse.

All factors taken into account, the effectiveness of the algorithm, the direction of the shift, and the dimensions of the grid should all be meticulously evaluated when creating a shift process for a two-dimensional grid in C++. Implementing grid shift operations can be smoothly carried out with the right data structures and approaches, unlocking a myriad of opportunities for computational geometry, computer graphics, and various other fields.

Example:

Imagine the scenario where we aim to simulate the movement of a player piece across a 2D grid symbolizing a game board. Our objective is to update the grid elements as the player progresses, visually illustrating the token's changing location. Let's consider a 3x3 matrix layout and focus on shifting the token horizontally to the right within this matrix.

We initially create a function in C++ to perform the shifting operation. This function takes the grid and the shift count as its input parameters. By traversing the grid, we transform it into a one-dimensional vector, which provides a more straightforward structure for manipulation.

To handle cases where the total number of shifts surpasses the grid dimensions, we proceed by calculating the adjusted number of shifts through the modulo operation with respect to the total grid size. Following this, we perform a right rotation on the elements of the grid that has been flattened, utilizing the inverse of the function. Finally, we restore the compressed grid back to its initial 2D structure.

Example:

Let's consider an example demonstrating the translation of a 2D Grid in C++:

Example

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

// Function to shift the 2D grid
vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
    int m = grid.size(); // Number of rows
    int n = grid[0].size(); // Number of columns

    // Flatten the grid into a 1D vector
    vector<int> flattenedGrid(m * n);
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            flattenedGrid[i * n + j] = grid[i][j];
        }
    }

    // Perform the shifting
    k %= (m * n); // Ensure k is within the range of elements
    reverse(flattenedGrid.begin(), flattenedGrid.end()); // Reverse the entire grid
    reverse(flattenedGrid.begin(), flattenedGrid.begin() + k); // Reverse the first k elements
    reverse(flattenedGrid.begin() + k, flattenedGrid.end()); // Reverse the remaining elements

    // Reshape the flattened grid back into a 2D grid
    vector<vector<int>> result(m, vector<int>(n));
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            result[i][j] = flattenedGrid[i * n + j];
        }
    }

    return result;
}

int main() {
    // Example usage
    vector<vector<int>> grid = {{1, 2, 3},
                                 {4, 5, 6},
                                 {7, 8, 9}};
    int k = 1; // Number of shifts

    vector<vector<int>> shiftedGrid = shiftGrid(grid, k);

    // Output the shifted grid
    for (const auto& row : shiftedGrid) {
        for (int value : row) {
            cout << value << " ";
        }
        cout << endl;
    }

    return 0;
}

Output:

Output

9 1 2 
3 4 5 
6 7 8

Explanation:

  • A 2D grid (vector>& grid) and the number of shifts (int k) constitute the input parameters for the shiftGrid function.
  • It determines how many rows (m) and columns (n) there are in the arrangement of columns and rows.
  • For simpler handling, the grid is subsequently compressed into a 1D vector (flattenedGrid).
  • The number of shifts k is guaranteed to be inside the permissible number of grid elements by the modulo operation.
  • The flattened grid's elements can be rotated by using the reverse function. The grid reverses itself in three stages: the first k elements are reversed, followed by the remaining elements.
  • The grid that has been flattened is reconfigured into a 2D grid (result) that has the same measurements that were used for the initial grid.
  • The moved grid is returned by the function.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience