1260. Shift 2D Grid*

1260. Shift 2D Grid*

https://leetcode.com/problems/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] becomes at grid[i][j + 1].
  • Element at grid[i][n - 1] becomes at grid[i + 1][0].
  • Element at grid[n - 1][n - 1] becomes at grid[0][0].
    Return the 2D grid after applying shift operation k times.

具体的例子看 Leetcode.

C++ 实现 1

把矩阵看成 1D 的数组, 会发现就是数据的循环移动…

class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        if (grid.empty() || grid[0].empty()) return {};
        int m = grid.size(), n = grid[0].size(), size = m * n;
        if (k % size == 0) return grid;
        k %= size;
        vector<int> tmp;
        for (int i = size - 1; i > size - 1 - k; -- i)
            tmp.push_back(grid[i / n][i % n]);
        for (int i = size - 1 - k; i >= 0; -- i)
            grid[(i + k) / n][(i + k) % n] = grid[i / n][i % n];
        for (int i = 0; i < k; ++i)
            grid[i / n][i % n] = tmp[k - 1 - i];
        return grid;
    }
};

C++ 实现 2

来自 LeetCode Submission.

class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        int sx = grid[0].size();
        int sy = grid.size();
        int os = sx * sy;
        
        vector<vector<int>> result(sy, vector<int>(sx));
        for (int y = 0; y < sy; y++) {
            for (int x = 0; x < sx; x++) {
                int index = (y * sx + x + k) % os;
                result[index/sx][index%sx] = grid[y][x];
            }
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值