LeetCode/二维网格迁移

给你一个 m 行 n 列的二维网格 grid 和一个整数 k,你需要将 grid 迁移 k 次

1. 直接映射

class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        int m = grid.size(), n = grid[0].size();
        vector<vector<int>> ret(m, vector<int>(n));
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                int index1 = (i * n + j + k) % (m * n);
                ret[index1 / n][index1 % n] = grid[i][j];
            }
        }
        return ret;
    }
};
转一维数组后移动k次(辅助一维数组映射)
class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
            int n = grid.size(), m = grid[0].size();
            vector<vector<int>> res = grid;
            vector<int> arr;
            //转存到一维数组
            for (int i = 0; i < n; i++) 
                for (int j = 0; j < m; j++) 
                    arr.push_back(grid[i][j]);
            //移动k次,也可以用一维辅助数组直接映射
            while(k-->0){
                int temp =arr.back();
                for(int i=arr.size()-1;i>0;i--)
                    arr[i] = arr[i-1];
                arr[0] = temp;
            }
            
            for (int i = 0; i < n; i++) 
                for (int j = 0; j < m; j++) 
                    res[i][j] = arr[i * m + j];
            return res;
        }
    };

2. 后移k次


class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        int m = grid.size();
        int n = grid[0].size();
        while(k-->0)
        {
            // 从最后一个元素开始移动
            int previous = grid[m-1][n-1];
            for (int i = 0; i < m; ++i)
                for (int j = 0; j < n; ++j)
                    swap(grid[i][j], previous);
        }
        
        return grid;
    }
};

3. 离谱写法

分别按行和列模拟操作
class Solution {
public:
    vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) {
        int m = grid.size();//行数
        int n = grid[0].size();//列数

        int right = k%n;//周期为n
        int down = k/n;//向下移动了down次
        down = down % m;//周期为m
        
        //先向下移动,再向右移动

        while(down-->0){
            vector<int> temp(grid[m-1]);
            for(int i=m-1;i>0;i--)
                grid[i] = grid[i-1];
             grid[0] = temp;
        }

        while(right-->0){
            vector<int> temp; 
            temp.push_back(grid[m-1][n-1]);
            for(int i =0;i<m-1;i++)
                temp.push_back(grid[i][n-1]);
            
            for(int j=n-1;j>0;j--)
                for(int i=0;i<m;i++)
                    grid[i][j] = grid[i][j-1];
            for(int i=0;i<m;i++)
                grid[i][0] = temp[i];
        }
        return grid;
    }
};
posted @ 2022-07-27 17:42  失控D大白兔  阅读(23)  评论(0编辑  收藏  举报