LeetCode 솔루션 분류

1260. Shift 2D Grid

컨텐츠 정보

본문

[LeetCode 시즌3] 2022년 4월10일 - 4월11일 문제 입니다.


[Easy] 1260Shift 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 grid[i + 1][0].
  • Element at grid[m - 1][n - 1] moves to grid[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]]

Example 2:

Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4
Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]]

Example 3:

Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9
Output: [[1,2,3],[4,5,6],[7,8,9]]

 

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m <= 50
  • 1 <= n <= 50
  • -1000 <= grid[i][j] <= 1000
  • 0 <= k <= 100

관련자료

댓글 3

핸디맨님의 댓글

  • 익명
  • 작성일
class Solution:
    def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
        numRows = len(grid)
        numCols = len(grid[0])
        
        for _ in range(k):
            prev = grid[-1][-1]
            for row in range(numRows):
                for col in range(numCols):
                    temp = grid[row][col]
                    grid[row][col] = prev
                    prev = temp
        return grid

mingki님의 댓글

  • 익명
  • 작성일
C++
Runtime: 19 ms, faster than 97.15% of C++ online submissions for Shift 2D Grid.
Memory Usage: 13.9 MB, less than 87.46% of C++ online submissions for Shift 2D Grid.
class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> res(m, vector<int>(n, 0));
        
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                int shifted_i = (i + ((j + k) / n)) % m;
                int shifted_j = (j + k) % n;
                
                res[shifted_i][shifted_j] = grid[i][j];
            }
        }
        return res;
    }
};

bobkim님의 댓글

  • 익명
  • 작성일
class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        int ColNum=grid[0].size();
        int RowNum=grid.size();
        int Rtmp, Ctmp;
        vector<vector<int>> gridShift(RowNum, vector<int>(ColNum,0));
        for(int i=0;i<RowNum;i++){
            for(int j=0;j<ColNum;j++){
                Rtmp=(i+(j+k)/ColNum)%RowNum;
                Ctmp=(j+k)%ColNum;
                gridShift[Rtmp][Ctmp]=grid[i][j];
            };
        };
        return gridShift; 
    }
};
LeetCode 솔루션 357 / 15 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


  • 현재 접속자 601 명
  • 오늘 방문자 7,427 명
  • 어제 방문자 7,890 명
  • 최대 방문자 14,831 명
  • 전체 회원수 1,540 명
알림 0