-
[Leetcode] 1260. Shift 2D Grid 문제 풀이Algorithm/문제풀이 2022. 4. 11. 16:44
https://leetcode.com/problems/shift-2d-grid/
Shift 2D Grid - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제 내용
2차원 배열을 k만큼 shift한 결과를 return
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]]
Example 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]]
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
문제 풀이
1차원 배열이면 그냥 k만큼 shift 하면 되지만 2차원 배열이라 y축도 고려해줘야 한다.
그래서 누산기처럼 carry 값을 이용해서 y축을 계산해서 shift 했다.
코드
class Solution { public: vector<vector<int>> shiftGrid(vector<vector<int>>& grid, int k) { int row = grid.size(); int col = grid[0].size(); vector<vector<int>> shiftedGrid(row, vector<int>(col)); for (int i = 0; i < row; ++i) { for (int j = 0; j < col; ++j) { int jj = (j + k) % col; int jc = (j + k) / col; int ii = (i + jc) % row; shiftedGrid[ii][jj] = grid[i][j]; } } return shiftedGrid; } };
'Algorithm > 문제풀이' 카테고리의 다른 글
[Leetcode] 59. Spiral Matrix II 문제 풀이 (0) 2022.04.13 [Leetcode] 289. Game of Life 문제 풀이 (0) 2022.04.12 [Leetcode] 682. Baseball Game 문제 풀이 (0) 2022.04.10 [Leetcode] 347. Top K Frequent Elements 문제 풀이 (0) 2022.04.09 [Leetcode] 703. Kth Largest Element in a Stream 문제 풀이 (0) 2022.04.08