Created
December 8, 2016 06:38
-
-
Save jianminchen/6e84dfcf2fb222d84900bda27687e6a1 to your computer and use it in GitHub Desktop.
HackerRank matrix rotation - Google semchyshyn - study code - Java Solution - calculation is interesting.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Solution { | |
public static void main(String[] args) { | |
int m, n, r, a[][]; | |
try (Scanner in = new Scanner(System.in)) { | |
m = in.nextInt(); | |
n = in.nextInt(); | |
r = in.nextInt(); | |
a = new int[m][]; | |
for (int i = 0; i < m; i++) { | |
a[i] = new int[n]; | |
for (int j = 0; j < n; j++) { | |
a[i][j] = in.nextInt(); | |
} | |
} | |
} | |
for (int i = 0; i < m; i++) { | |
for (int j = 0; j < n; j++) { | |
if (j > 0) { | |
System.out.print(' '); | |
} | |
int layer = Math.min(Math.min(i, j), Math.min(m - i - 1, n - j - 1)); | |
int length = 2*n + 2*m - 8*layer - 4; | |
int position = i == layer ? j - layer : | |
n - j - 1 == layer ? n + i - 3*layer - 1 : | |
m - i - 1 == layer ? m + 2*n - j - 5*layer - 3 : | |
2*m + 2*n - 7*layer - i - 4; | |
int rotated = (position + r) % length; | |
int value = rotated < n - 2*layer ? a[layer][rotated + layer] : | |
rotated < m + n - 4*layer - 1 ? a[rotated - n + 3*layer + 1][n - layer - 1] : | |
rotated < m + 2*n - 6*layer - 2 ? a[m - layer - 1][m + 2*n - 5*layer - 3 - rotated] : | |
a[2*m + 2*n - 7*layer - 4 - rotated][layer]; | |
System.out.print(value); | |
} | |
System.out.println(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment