Skip to content

Instantly share code, notes, and snippets.

@1kohei1
Last active December 12, 2015 17:53
Show Gist options
  • Save 1kohei1/278395e592f9c820a693 to your computer and use it in GitHub Desktop.
Save 1kohei1/278395e592f9c820a693 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
public class Playground {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int row = scanner.nextInt();
int col = scanner.nextInt();
int numRotations = scanner.nextInt();
int[][] map = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
map[i][j] = scanner.nextInt();
}
}
// Rotate
int rowStart = 0;
int colStart = 0;
while(rowStart * 2 < row && colStart * 2 < col) {
// Calculate how many rotations must occur
int numElements = (row - (rowStart * 2) - 1) * 2 + (col - (colStart * 2) - 1) * 2;
int rotations = numRotations % numElements;
// Get the elements in the circle
int[] line = new int[numElements];
int count = 0;
// Top
for (int i = colStart; i < col - colStart - 1; i++) {
line[count] = map[rowStart][i];
count++;
}
// Right
for (int i = rowStart; i < row - rowStart - 1; i++) {
line[count] = map[i][col - colStart - 1];
count++;
}
// Bottom
for (int i = col - colStart - 1; i > colStart; i--) {
line[count] = map[row - rowStart - 1][i];
count++;
}
// Left
for (int i = row - rowStart - 1; i > rowStart; i--) {
line[count] = map[i][colStart];
count++;
}
// Put them back
count = rotations;
// Top
for (int i = colStart; i < col - colStart - 1; i++) {
map[rowStart][i] = line[count];
count++;
if (count == numElements) count = 0;
}
// Right
for (int i = rowStart; i < row - rowStart - 1; i++) {
map[i][col - colStart - 1] = line[count];
count++;
if (count == numElements) count = 0;
}
// Bottom
for (int i = col - colStart - 1; i > colStart; i--) {
map[row - rowStart - 1][i] = line[count];
count++;
if (count == numElements) count = 0;
}
// Left
for (int i = row - rowStart - 1; i > rowStart; i--) {
map[i][colStart] = line[count];
count++;
if (count == numElements) count = 0;
}
rowStart++;
colStart++;
}
printMap(map, row, col);
}
public static void printMap(int[][] map, int row, int col) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.printf("%d ", map[i][j]);
}
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment