Created
April 15, 2016 01:48
-
-
Save jianminchen/c234a238ea331ea9a037d603c37a6649 to your computer and use it in GitHub Desktop.
Matrix Rotation - solution to study
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
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
class Solution | |
{ | |
static void Main(String[] args) | |
{ | |
int[] ia = GetInts(Console.ReadLine(), 3); | |
int rows = ia[0]; | |
int cols = ia[1]; | |
int cnt = ia[2]; | |
int[][] mx = new int[rows][]; | |
for (int i = 0; i < rows; i++) | |
{ | |
mx[i] = GetInts(Console.ReadLine(), cols); | |
} | |
Rotate(mx, rows, cols, cnt); | |
for (int i = 0; i < rows; i++) | |
{ | |
Console.WriteLine(GetRow(mx[i])); | |
} | |
} | |
private static void Rotate(int[][] mx, int rows, int cols, int cnt) | |
{ | |
int startR = 0, startCol = 0; | |
while (rows > 1 && cols > 1) | |
{ | |
RotateOut(mx, rows, cols, startR, startCol, cnt); | |
rows -= 2; | |
cols -= 2; | |
startR++; | |
startCol++; | |
} | |
} | |
private static string GetRow(int[] xx) | |
{ | |
string res = ""; | |
foreach (int i in xx) | |
{ | |
res += i + " "; | |
} | |
return res.Trim(); | |
} | |
private static void RotateOut(int[][] mx, int rows, int cols, int startR, int startCol, int cnt) | |
{ | |
cnt = cnt % (2 * (cols + rows - 2)); | |
for (int x = 0; x < cnt; x++) | |
{ | |
int t = mx[startR][startCol]; | |
for (int i = startCol; i < startCol + cols - 1; i++) | |
mx[startR][i] = mx[startR][i + 1]; | |
int c = startCol + cols - 1; | |
for (int i = startR; i < startR + rows - 1; i++) | |
mx[i][c] = mx[i + 1][c]; | |
int r = startR + rows - 1; | |
for (int i = startCol + cols - 1; i >= startCol + 1; i--) | |
mx[r][i] = mx[r][i - 1]; | |
for (int i = startR + rows - 1; i >= 1 + startR; i--) | |
mx[i][startCol] = mx[i - 1][startCol]; | |
mx[startR + 1][startCol] = t; | |
} | |
} | |
static int[] GetInts(string inp, int cnt) | |
{ | |
string[] vals = inp.Split(new char[] { ' ' }); | |
int[] res = new int[cnt]; | |
for (int i = 0; i < cnt; i++) | |
{ | |
res[i] = Convert.ToInt32(vals[i]); | |
} | |
return res; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment