Created
April 15, 2016 04:15
-
-
Save jianminchen/6e3ca88e8633ad8bace8387f154904df to your computer and use it in GitHub Desktop.
Matrix Rotation - with bugs
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 RotateArray2 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
string s1 = Console.ReadLine(); | |
string[] sA = s1.Split(' '); | |
int row = Convert.ToInt16(sA[0].Trim()); | |
int col = Convert.ToInt16(sA[1].Trim()); | |
int T = Convert.ToInt16(sA[2].Trim()); | |
int[][] arr = new int[row][]; | |
for (int i = 0; i < row; i++) | |
arr[i] = new int[col]; | |
for (int i = 0; i < row; i++) | |
{ | |
string s = Console.ReadLine(); | |
string[] aA = s.Split(' '); | |
if (aA.Length != col) | |
return; | |
for (int j = 0; j < col; j++) | |
arr[i][j] = Convert.ToInt16(aA[j].Trim()); | |
} | |
for (int i = 0; i < T; i++) | |
rotateArrayOneStepAntiClockwise(arr); | |
for (int i = 0; i < row; i++) | |
{ | |
string s = ""; | |
for (int j = 0; j < col; j++) | |
s += arr[i][j].ToString() + " "; | |
Console.WriteLine(s); | |
} | |
} | |
/* | |
* Do it in place | |
*/ | |
public static bool rotateArrayOneStepAntiClockwise(int[][] arr) | |
{ | |
if (arr == null) return false; | |
int row = arr.Length; // row | |
int col = arr[0].Length; // column | |
int start = 0; | |
int end = col - 1; | |
while (start <= end && start < row / 2 && start < col / 2) | |
{ | |
int totalRow = row - 2 * start; | |
int totalCols = col - 2 * start; | |
int firstRow = start; | |
//int LastRow = totalRow - 1; // math is wrong for last row | |
int lastRow = row - start - 1; | |
int firstCol = start; | |
int lastCol = end; | |
int tmpValue = arr[start][start]; | |
// for up row Direction: L -> R | |
for (int i = firstCol + 1; i <= lastCol; i++ ) | |
arr[firstRow][i - 1] = arr[firstRow][i]; | |
// for right column Direction: top -> down | |
for (int i = firstRow + 1; i <= lastRow; i++) | |
arr[i - 1][lastCol] = arr[i][lastCol]; | |
// for down row - Direction: R -> L | |
for (int i = lastCol; i > firstCol ; i-- ) | |
arr[lastRow][i] = arr[lastRow][i - 1]; | |
// for left column - Direction: Down -> up first 2 rows - no touch | |
for (int i = lastRow; i >= firstRow + 2 ; i--) // | |
arr[i][firstCol] = arr[i - 1][firstCol]; | |
arr[firstRow + 1][firstCol] = tmpValue; | |
start++; | |
end--; | |
} | |
return true; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment