Created
December 7, 2016 05:48
-
-
Save jianminchen/8ee835834a9a6cdb68331695a3c1abb1 to your computer and use it in GitHub Desktop.
HackerRank Matrix Rotation - code review - No. 1, code review
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