diff --git a/Java/CyclicallyRotatingGrid.java b/Java/CyclicallyRotatingGrid.java new file mode 100644 index 00000000..27d927c0 --- /dev/null +++ b/Java/CyclicallyRotatingGrid.java @@ -0,0 +1,30 @@ +//https://leetcode.com/contest/weekly-contest-247/problems/cyclically-rotating-a-grid/ + +// Very nice problem! + +class Solution { + public int[][] rotateGrid(int[][] a, int K) { + int n = a.length, m = a[0].length; + for(int T = 0, D = n-1, L = 0, R = m-1;L <= R && T <= D;T++,D--,L++,R--){ + int pe = 2*(n-1-T*2) + 2*(m-1-T*2); + int lk = K % pe; + for(int t = 0;t < lk;t++){ + int temp = a[T][L]; + for(int s = L+1;s <= R;s++){ + a[T][s-1] = a[T][s]; + } + for(int s = T+1;s <= D;s++){ + a[s-1][R] = a[s][R]; + } + for(int s = R-1;s >= L;s--){ + a[D][s+1] = a[D][s]; + } + for(int s = D-1;s >= T+1;s--){ + a[s+1][L] = a[s][L]; + } + a[T+1][L] = temp; + } + } + return a; + } +} diff --git a/README.md b/README.md index 1dcb41a5..c77f89ba 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,7 @@ Check out ---> [Sample PR](https://github.com/codedecks-in/LeetCode-Solutions/pu | 36 | [Valid Sudoku](https://leetcode.com/problems/valid-sudoku/) | [Java](./Java/valid-sudoku.java) | O(N^2) | O(N) | Medium | Array, 2D Matrix | | 1512 | [Number of Good Pairs](https://leetcode.com/problems/number-of-good-pairs/) | [Java](./Java/Number-of-Good-Pairs.java) | O(N^2) | O(1) | Easy | Array | | 162 | [Find Peak element](https://leetcode.com/problems/find-peak-element/) | [javascript](https://github.com/codedecks-in/LeetCode-Solutions/blob/master/JavaScript/findPeakElement.js) | o(Logn) | O(1) | Medium | Array | +| 1914 | [Cyclically Rotating a Grid](https://leetcode.com/problems/cyclically-rotating-a-grid/) | [Java](./Java/CyclicallyRotatingGrid.java)| O((m+n)^3) | O(1) | Medium | Array, Matrix | | 54 | [Spiral Matrix](https://leetcode.com/problems/spiral-matrix/) | [C++](./C++/Spiral-matrix.cpp) | O(M\*N) | O(M\*N) | Medium | Array | | 238 | [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/) | [C++](./C++/238.Product_of_array_except_self) | O(N) | O(N) | Medium | Array |