[LeetCode] Shift 2D Grid

아르당·2026년 4월 14일

LeetCode

목록 보기
260/303
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

크기가 m x n 인 2D grid와 정수 k가 주어진다. grid를 k번 옮겨야 한다.
한 번 옮기는 작업은 다음과 같다.

  • grid[i][j]는 grid[i][j + 1]으로 옮긴다.
  • grid[i][n - 1]는 grid[i + 1][0]으로 옮긴다.
  • grid[m - 1][n - 1]는 grid[0][0]으로 옮긴다.

k번 옮긴 작업을 적용한 후 2D gird를 반환해라.

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]]

#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]]

#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

Solved

class Solution {
    public List<List<Integer>> shiftGrid(int[][] grid, int k) {
        List<List<Integer>> result = new ArrayList();
        int rows = grid.length;
        int cols = grid[0].length;

        for(int i = 0; i < rows; i++){
            result.add(new ArrayList());
        }

        k %= rows * cols;
        
        int totalCell = rows * cols;
        int start = totalCell - k;
        int count = 0;

        for(int i = start; i < start + totalCell; i++){
            int row = (i / cols) % rows;
            int col = i % cols;

            result.get(count / cols).add(grid[row][col]);
            count++;
        }

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글