Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created May 26, 2017 20:59
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/8716429b6dd9c92bc2499b5f77135ae1 to your computer and use it in GitHub Desktop.
Save jianminchen/8716429b6dd9c92bc2499b5f77135ae1 to your computer and use it in GitHub Desktop.
Rotate image - Leetcode 48 - first reverse up to down, and then swap the symmetry. Pass online judge.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RotateImage_SimpleOne
{
/// <summary>
/// study the rotate image - Leetcode discussion
/// https://leetcode.com/problems/rotate-image/#/description
///
/// </summary>
class Program
{
static void Main(string[] args)
{
}
/*
* clockwise rotate
* first reverse up to down, then swap the symmetry
* 1 2 3 7 8 9 7 4 1
* 4 5 6 => 4 5 6 => 8 5 2
* 7 8 9 1 2 3 9 6 3
*/
private static void rotate(int[,] matrix) {
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
int index = 0;
while (2 * index < rows )
{
reverseRows(index, rows -1 - index, matrix);
index++;
}
for (int row = 0; row < rows; ++row)
{
for (int col = row + 1; col < cols; ++col)
{
swap(row, col, matrix);
}
}
}
private static void reverseRows(int row1, int row2, int[,] matrix)
{
int cols = matrix.GetLength(1);
for (int col = 0; col < cols; col++)
{
int tmp = matrix[row1, col];
matrix[row1, col] = matrix[row2, col];
matrix[row2, col] = tmp;
}
}
private static void swap(int row, int col, int[,] matrix)
{
int tmp = matrix[row, col];
matrix[row, col] = matrix[col, row];
matrix[col, row] = tmp;
}
/*
* anticlockwise rotate
* first reverse left to right, then swap the symmetry
* 1 2 3 3 2 1 3 6 9
* 4 5 6 => 6 5 4 => 2 5 8
* 7 8 9 9 8 7 1 4 7
*/
void anti_rotate(int[,] matrix) {
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
reverseTwoCols(0, cols - 1, matrix);
for (int row = 0; row < rows; ++row)
{
for (int col = row + 1; col < cols; ++col)
{
swap(row, col, matrix);
}
}
}
private static void reverseTwoCols(int row, int col, int[,] matrix)
{
}
public void Rotate(int[,] matrix) {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment