Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created April 15, 2016 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/6e2ca0ac395913646ed012c40c283e7f to your computer and use it in GitHub Desktop.
Save jianminchen/6e2ca0ac395913646ed012c40c283e7f to your computer and use it in GitHub Desktop.
Matrix rotation - study the code
using System;
using System.Collections.Generic;
using System.Linq;
namespace HRank
{
class Program
{
static public char[] before = new char[0];
static public char[] after = new char[0];
static void Main(string[] args)
{
string[] vars = Console.ReadLine().Split(' ').ToArray();
int rotates = Convert.ToInt32(vars[2]);
int rows = Convert.ToInt32(vars[0]);
int cols = Convert.ToInt32(vars[1]);
int temp = -1;
int[,] matrix = new int[rows, cols];
for (int i = 0; i < rows; i++)
{
string[] input = Console.ReadLine().Split(' ').ToArray();
for (int j = 0; j < cols; j++)
matrix[i, j] = Convert.ToInt32(input[j]);
}
//while(rotates > 0)
//{
// rotates--;
int minCornerX = 0;
int minCornerY = 0;
int maxCornerX = rows - 1;
int maxCornerY = cols - 1;
int y = 0;
int x = 0;
while (minCornerX < maxCornerX && minCornerY < maxCornerY)
{
int reduce = ((maxCornerX - minCornerX) + 1) * 2 + ((maxCornerY - minCornerY - 1) * 2);
int rotated = 0;
while (rotated + reduce <= rotates)
rotated += reduce;
while (rotated < rotates)
{
rotated++;
//rotate col down
temp = matrix[maxCornerX, minCornerY];
for (x = maxCornerX; x > minCornerX; x--)
{
matrix[x, minCornerY] = matrix[x - 1, minCornerY];
}
//rotate row right
int temp2 = matrix[maxCornerX, maxCornerY];
for (y = maxCornerY; y > minCornerY + 1; y--)
{
matrix[maxCornerX, y] = matrix[maxCornerX, y - 1];
}
matrix[maxCornerX, y] = temp;
//rotate col up
temp = matrix[minCornerX, maxCornerY];
for (x = minCornerX; x < maxCornerX - 1; x++)
{
matrix[x, maxCornerY] = matrix[x + 1, maxCornerY];
}
matrix[x, maxCornerY] = temp2;
//rotate row left
for (y = minCornerY; y < maxCornerY - 1; y++)
{
matrix[minCornerX, y] = matrix[minCornerX, y + 1];
}
matrix[minCornerX, y] = temp;
}
minCornerX++;
minCornerY++;
maxCornerY--;
maxCornerX--;
}
//}
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
Console.Write(matrix[i, j] + " ");
Console.WriteLine();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment