Created
September 18, 2011 19:44
-
-
Save andy722/1225471 to your computer and use it in GitHub Desktop.
Rotate int matrix by 90 degrees
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.io.FileInputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.io.PrintWriter; | |
import java.util.Scanner; | |
public class MatrixRotator { | |
public static void main(String[] args) throws IOException { | |
new MatrixRotator().rotate90(new FileInputStream("test.txt"), System.out); | |
} | |
public void rotate90(InputStream in, OutputStream out) throws IOException { | |
final int m[][] = readMatrix(in); | |
rotate90(m); | |
print(m, out); | |
} | |
/* Rotation */ | |
private void rotate90(int m[][]) { | |
final int dim = m.length; | |
for (int n = 0; n < dim; n++) { | |
rotate90(m, n, dim - n, n, dim - n); | |
} | |
} | |
private void rotate90(int m[][], int minY, int maxY, int minX, int maxX) { | |
assert (maxX < minX); | |
assert (maxY < minY); | |
final int length = maxX - minX; | |
for (int i = 0; i < length - 1; i++) { | |
final int tmp = m[minY][minX + i]; | |
m[minY][minX + i] = m[maxY - i - 1][minX]; | |
m[maxY - i - 1][minX] = m[maxY - 1][maxX - i - 1]; | |
m[maxY - 1][maxX - i - 1] = m[minY + i][maxX - 1]; | |
m[minY + i][maxX - 1] = tmp; | |
} | |
} | |
/* IO utilities */ | |
private int[][] readMatrix(InputStream in) { | |
final Scanner s = new Scanner(in); | |
final int dim = s.nextInt(); | |
final int matrix[][] = new int[dim][dim]; | |
for (int i = 0; i < dim; i++) { | |
for (int j = 0; j < dim; j++) { | |
matrix[i][j] = s.nextInt(); | |
} | |
} | |
return matrix; | |
} | |
private void print(int matrix[][], OutputStream out) { | |
final PrintWriter p = new PrintWriter(out); | |
final int dim = matrix.length; | |
for (int i = 0; i < dim; i++) { | |
for (int j = 0; j < dim; j++) { | |
p.print(matrix[i][j] + " "); | |
} | |
p.println(); | |
} | |
p.flush(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment