Skip to main content

Command Palette

Search for a command to run...

LeetCode Solution, Easy, 1260. Shift 2D Grid

移動 2D 矩陣

Published
LeetCode Solution, Easy, 1260. Shift 2D Grid

I am not a programmer just a leaner. Writing JavaScript, Python, and Go and doing something on Kubernetes.

1260. 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 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:

e1.png

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:

e2.png

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

Hint 1:

Simulate step by step. move grid[i][j] to grid[i][j+1]. handle last column of the grid.

Hint 2:

Put the matrix row by row to a vector. take k % vector.length and move last k of the vector to the beginning. put the vector to the matrix back the same way.

題目翻譯

這題會給一個 m x n 的二維矩陣,和一個整數 k。需要將此矩陣的內容移動 k 的位置。如範例的圖示。

解法解析

這題有幾種解法,但最主要的重點就在於怎麼去計算索引。

第一種解法概念,類似於 189. Rotate Array,將二維矩陣視為一維的陣列。挪移位置後再重新拆回矩陣。Kotlin 的解法就是類似這個方式處理。

第二種解法概念,就是直接找出索引的計算規則,以下的程式範例就是使用此種方式

解法範例

Go

func shiftGrid(grid [][]int, k int) [][]int {
    numRows := len(grid)
    numCols := len(grid[0])
    var newGrid [][]int

    for row := 0; row < numRows; row++ {
        var newRow []int
        for col := 0; col < numCols; col++ {
            idx := row*numCols + col - k
            for idx < 0 {
                idx += numCols * numRows
            }

            newRow = append(newRow, grid[idx/numCols][idx%numCols])
        }
        newGrid = append(newGrid, newRow)
    }
    return newGrid
}

JavaScript

/**
 * @param {number[][]} grid
 * @param {number} k
 * @return {number[][]}
 */
var shiftGrid = function (grid, k) {
    const numRows = grid.length,
        numCols = grid[0].length;
    const newGrid = [];
    for (let i = 0; i < numRows; i++) {
        newGrid[i] = new Array(numCols).fill(0);
    }

    for (let row = 0; row < numRows; row++) {
        for (let col = 0; col < numCols; col++) {
            const newCol = (col + k) % numCols;
            const newRow = (row + Math.floor((col + k) / numCols)) % numRows;
            newGrid[newRow][newCol] = grid[row][col];
        }
    }

    return newGrid;
};

Kotlin

class Solution {
    fun shiftGrid(grid: Array<IntArray>, k: Int): List<List<Int>> {
        val newGrid = mutableListOf<MutableList<Int>>()
        val numRows = grid.size
        val numCols = grid[0].size
        val total = numRows * numCols
        val sub = k % total

        for (b in 0..numRows - 1) newGrid.add(mutableListOf<Int>())
        for (a in 0..total - 1) {
            val idx = (a - sub + total) % total
            newGrid.get(a / numCols).add(grid[idx / numCols][idx % numCols])
        }

        return newGrid
    }
}

PHP

class Solution
{

    /**
     * @param Integer[][] $grid
     * @param Integer $k
     * @return Integer[][]
     */
    function shiftGrid($grid, $k)
    {
        $numRows = count($grid);
        $numCols = count($grid[0]);
        $newGrid = array_fill(0, $numRows, array_fill(0, $numCols, 0));

        for ($row = 0; $row < $numRows; $row++) {
            for ($col = 0; $col < $numCols; $col++) {
                $newCol = ($col + $k) % $numCols;
                $newRow = ($row + floor(($col + $k) / $numCols)) % $numRows;
                $newGrid[$newRow][$newCol] = $grid[$row][$col];
            }
        }
        return $newGrid;
    }
}

Python

class Solution:
    def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
        num_rows, num_cols = len(grid), len(grid[0])
        new_grid = [[0] * num_cols for _ in range(num_rows)]
        for row in range(num_rows):
            for col in range(num_cols):
                new_col = (col + k) % num_cols
                new_row = (row + (col + k) // num_cols) % num_rows
                new_grid[new_row][new_col] = grid[row][col]
        return new_grid

Rust


Swift

class Solution {
  func shiftGrid(_ grid: [[Int]], _ k: Int) -> [[Int]] {
    let numRows = grid.count
    let numCols = grid[0].count
    var newGrid = [[Int]](repeating: [Int](repeating: 0, count: numCols), count: numRows)
    for row in 0..<numRows {
      for col in 0..<numCols {
        let newCol = (col + k) % numCols
        let newRow = (row + ((col + k) / numCols)) % numRows
        newGrid[newRow][newCol] = grid[row][col]
      }
    }

    return newGrid
  }
}

LeetCode Solution

Part 1 of 50

A collection of leetcode solustion

More from this blog

如何開始入門軟體工程領域 - 名詞解釋(長期更新)

現在應該開始有很多人想要踏入軟體工程的領域,但在進入這個領域之前,覺得先了解一些名詞,可以在入門時更有方向也更知道要用什麼關鍵字去找尋有用的資訊。這篇文章就是想要幫助想要入門的人理解一些軟體工程裡的專有名詞。 作業系統 這一區塊主要解釋跟作業系統層面相關的名詞 英文中文解釋 Operation system 簡稱 OS | 作業系統 | 就是電腦的作業系統,是三大作業系統分別是:Linux、Windows、macOS | | Linux | | 自由和開放原始碼的 UNI...

May 10, 2023

我的 MacBook Pro (Apple Silicon) 設定

現在開始因為 ChatGPT 的出現,各種 AI 助手的功能都跑出來了。想想自己用了許久的環境設定也應該要來重新審視和建立新的開發環境了,僅此紀錄我個人的環境配置步驟和設定。 環境前置步驟 還原 MacBook Pro 至全新環境 macOS(全部資料刪除) 設定好初始設定後,登入 Apple ID 進入 App Store 確定 macOS 版本和預設 APP 都更新到最新 macOS 版本 到系統設定調整所有設定至個人習慣的設定 三指拖移 觸控板手勢開啟 防火牆開啟 輸入法設定...

Apr 25, 2023

ChatGPT 下的發展預想

從 ChatGPT 問世到現在,有許許多多的文章和討論出來。先從最早的 Google 要完蛋了,到後來的工作要被取代了,工程師失業了。 我就比較沒有想要馬上出來評論一下,我喜歡讓子彈飛一會兒。跟討論一下我自己比較在意的討論點。 Google 為什麼慢了? 結論:因為他需要更小心 很多人說 Google 怎麼被微軟搶先了一步。剛開始 Bing 說要加上 AI 的時候大家都在說 Google 怎麼慢了。我就馬上跑去看 OpenAI 的網站,靠北呀啊就 Azure 贊助的。那當然在正式上線 ChatG...

Mar 23, 2023

不工程的攻城獅

223 posts

I am not a programmer because I am not good at programming. But I do programming. Love to learn new things. An animal lover and a dancer. My oshi is 潤羽るしあ.