classSolution: defshiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]: m, n = len(grid), len(grid[0]) ans = [[0] * n for _ inrange(m)] for i, row inenumerate(grid): for j, v inenumerate(row): index1 = (i * n + j + k) % (m * n) ans[index1 // n][index1 % n] = v return ans
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { 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; } };
publicclassSolution { public IList<IList<int>> ShiftGrid(int[][] grid, int k) { int m = grid.Length, n = grid[0].Length; IList<IList<int>> ret = new List<IList<int>>(); for (int i = 0; i < m; i++) { IList<int> row = new List<int>(); for (int j = 0; j < n; j++) { row.Add(0); } ret.Add(row); } 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; } }
[sol1-C]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int** shiftGrid(int** grid, int gridSize, int* gridColSize, int k, int* returnSize, int** returnColumnSizes){ int m = gridSize, n = gridColSize[0]; int **ret = (int **)malloc(sizeof(int *) * m); *returnColumnSizes = (int *)malloc(sizeof(int) * m); for (int i = 0; i < m; i++) { ret[i] = (int *)malloc(sizeof(int) * n); (*returnColumnSizes)[i] = 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]; } } *returnSize = m; return ret; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
var shiftGrid = function(grid, k) { const m = grid.length, n = grid[0].length; const ret = []; for (let i = 0; i < m; i++) { const row = []; for (let j = 0; j < n; j++) { row.push(0); } ret.push(row); } for (let i = 0; i < m; i++) { for (let j = 0; j < n; j++) { const index1 = (i * n + j + k) % (m * n); ret[Math.floor(index1 / n)].splice(index1 % n, 1, grid[i][j]); } } return ret; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
funcshiftGrid(grid [][]int, k int) [][]int { m, n := len(grid), len(grid[0]) ans := make([][]int, m) for i := range ans { ans[i] = make([]int, n) } for i, row := range grid { for j, v := range row { index1 := (i*n + j + k) % (m * n) ans[index1/n][index1%n] = v } } return ans }