Created
April 6, 2016 01:25
-
-
Save jianminchen/e489cf7a490ac426eb50b4300890387d to your computer and use it in GitHub Desktop.
Matrix Rotate 90 degree clockwise -
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.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace rotateMatrix90DegreeClockWise | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
} | |
public static bool rotateInplace90ClockWise(int[][] arr) | |
{ | |
if (arr == null || arr.Length == 0 || arr[0].Length == 0) return false; | |
int n = arr.Length; // row | |
int m = arr[0].Length; // column | |
if (n != m) return false; | |
// we need to start loops | |
int start = 0; | |
int end = n - 1; | |
while (start < end && start < n / 2 && end < n / 2) | |
{ | |
// top with right swap - left the terminal point untouched | |
// left to right <- row | |
// top to down <- column | |
for (int i = start + 1; i < end - 1; i++) | |
{ | |
int currx = start; | |
int curry = i; | |
int currx_col = i; | |
int curry_col = end; | |
swap(arr, currx, curry, currx_col, curry_col); | |
} | |
// now, top down, we need to cross swap | |
for (int i = start + 1; i < end - 1; i++) | |
{ | |
int currx = start; | |
int curry = i; | |
int currx_down = end; | |
int curry_down = end - i; | |
swap(arr, currx, curry, currx_down, curry_down); | |
} | |
// left and top swap | |
for (int i = start + 1; i < end - 1; i++) | |
{ | |
// left part | |
int currx = end - 1 - i; | |
int curry = start; | |
int currx_top = start; | |
int curry_top = i; | |
swap(arr, currx, curry, currx_top, curry_top); | |
} | |
// and then, rotate four corners | |
// 1, 2 | |
// 4 3 | |
swap(arr, start, start, start, end); | |
swap(arr, end, end, start, start); | |
swap(arr, start, start, end, start); | |
start++; | |
end--; | |
} | |
return true; | |
} | |
private static void swap(int[][] arr, int x, int y, int x2, int y2) | |
{ | |
int tmp = arr[x][y]; | |
arr[x][y] = arr[x2][y2]; | |
arr[x2][y2] = tmp; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment