본문 바로가기

Algorithm/Implementation

(C++) - LeetCode (easy) 1260. Shift 2D Grid

반응형

https://leetcode.com/problems/shift-2d-grid/description/

 

Shift 2D Grid - LeetCode

Can you solve this real interview question? Shift 2D Grid - 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 to grid[i][j + 1]. * Element at grid[i][n - 1] moves to

leetcode.com

행렬 동작 구현 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

바뀐 행렬 shiftedGrid를 선언 후 grid로 초기화해줍니다.

📔 풀이과정

k번 만큼 loop를 수행하며 다음을 진해해줍니다.

1. index overflow가 나지 않도록 지정된 변환을 수행해 shiftedGrid에 grid의 값을 넣어줍니다.

2. 변환된 값을 다시 grid에 복사해줍니다.

 

📔 정답 출력 | 반환

shiftedGrid를 반환해줍니다.


📕 Code

📔 C++

class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        vector<vector<int>> shiftedGrid = grid;
        int m = grid.size();
        int n = grid[0].size();
        while(k--) {
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    if(j+1 < n) shiftedGrid[i][j+1] = grid[i][j];
                    if(i+1 < m) shiftedGrid[i+1][0] = grid[i][n-1];
                }
            }
            shiftedGrid[0][0] = grid[m-1][n-1];
            grid = shiftedGrid;
        }
        return shiftedGrid;
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.